在 null laravel 上调用成员函数 save()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35988648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:24:44  来源:igfitidea点击:

Call to a member function save() on null laravel

phplaravellaravel-5

提问by garden

Hello guys I'm using laravel 5 polymorphic relation to save the data in the database but I'm facing some problem. When ever I try to save the data in the database it is throwing me this error

大家好,我正在使用 laravel 5 多态关系将数据保存在数据库中,但我遇到了一些问题。每当我尝试将数据保存在数据库中时,它都会向我抛出此错误

Call to a member function save() on null

在 null 上调用成员函数 save()

I don't know why I'm facing this error. I'm following this tutorial fot the polymorphic relation Creating Polymorphic Relations in Laravel 5.

我不知道为什么我面临这个错误。我正在关注有关多态关系在 Laravel 5 中创建多态关系的教程

I 'm making a polymorphic relation like this. A post and comment can have many likes.

我正在制作这样的多态关系。一个帖子和评论可以有很多赞。

The like Request validates that if I'm sending a id then this request should be entertained otherwise not

类似请求验证如果我发送一个 id 那么这个请求应该被受理,否则不会

Like Controller

喜欢控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Requests\LikeRequest;
use App\Commands\LikeCommand;
// use App\Commands\ReadLikeCommand;
use App\Http\Controllers\Controller;



use Illuminate\Bus\Dispatcher;
// use App\Transformers\PostTransformer;
use Exception;
// use App\Events\TestEvent;
use App\Exceptions\Custom\NotPermissionException;
use App\Exceptions\Custom\NameNotFound;
class LikeController extends Controller
{

    public function likeComment(LikeRequest $data){
        try{
            $render = $this->dispatch(new LikeCommand("comment" , $data));
        }catch(Exception $e){
            $e->getMessage();
        }
    }

    public function likePost(LikeRequest $data){
        error_log("1");
        try{
            $render = $this->dispatch(new LikeCommand("post" , $data));
        }catch(Exception $e){
            error_log("error : ".$e->getMessage());
        }
    }
}

Like Command

喜欢命令

<?php

namespace App\Commands;

use App\Commands\Command;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Foundation\Bus\DispatchesJobs;
use App\Repositories\LikeRepository;
use Exception;
use DB;
use App\LikeModel;
use Artisan;


use App\Repositories\PostRepository;

class LikeCommand extends Command implements SelfHandling
{

    use DispatchesJobs;


    private $postId;
    private $action;
    private $data;




    /**
     * Create a new command instance.
     *
     * @param $request
     *
     * @internal param $email
     * @internal param $phone
     * @internal param $comments
     * @internal param $name
     */

    public function __construct($action,$request)
    {
        $this->action = $action;
        $this->postId = $request->id;
        $this->data = $request;
        error_log("Hello in the construct");
    }

    /**
     * Execute the command.
     *
     * @param TestRepository $TestRepository
     */
    public function handle(LikeRepository $LikeRepo, PostRepository $postRepo )
    {  

        error_log("Hello");
        error_log("A : ".$this->action );
        error_log("ID : ".$this->postId);

        if($this->action =="comment"){
            error_log("in like comment");
          return  $LikeRepo->LikeComment( $this->postId);
        }else if ($this->action == "post"){ 
            error_log("2");
           return $LikeRepo->LikePost( $this->postId, $postRepo , );
        }


    }
}

Like Repo

喜欢回购

<?php

namespace App\Repositories;

use App\Repositories\CommentRepository;
use App\Repositories\PostRepository;
use App\CommentModel;
use App\LikeModel;
class LikeRepository
{
    public function create($comment)
    {
        // error_log("Trying to save now. Let's see");
         $Like = new LikeModel;
        $Like->post_id = $comment;
        // $Comment->post_id = $this->post_id;
        $comment->save();

    }   
    public function LikeComment($id) {
        // return CommentModel::where('post_id' , $id)->get();
        // return CommentModel::get();
    }

    public function LikePost($id, PostRepository $postRepo){
        error_log("3");
        $result = $postRepo->getById($id);
        error_log("4");


        // $Like = DB::transaction(function () use ($LikeRepository) {
        $Like = new likeModel;
        error_log("5");
        $result->Like->save($like);
        error_log("6");
        $Like->status="success";
        // });
        return $Like;
    }
}

Like Model

喜欢模特

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class LikeModel extends Model
{
    public $table = "likes";
    //
    public function likeable()
    {
      return $this->morphTo();
    }
}

Post Model

岗位模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class PostModel extends Model
{

    //
    public $table = "posts";

    public function likes()
    {
      return $this->morphMany('App\Like', 'likeable');
    }
}

Comment Model

评论模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class CommentModel extends Model
{
    //
    public $table = "comments";

    public function likes()
    {
      return $this->morphMany('App\Like', 'likeable');
    }
}

UpdateI solved this problem by changing $result->Like->save($like);to this $result->likes->save($like);and int he PostModel I had to change App\Likesto App\LikeModelsimilarly in CommentModel but now it's throwing me this error error : Method save does not exist.

更新我改变解决了这个问题,$result->Like->save($like);$result->likes->save($like);和诠释,他PostModel我不得不改变App\Likes,以App\LikeModel同样的CommentModel但现在它扔我这个错误error : Method save does not exist.

采纳答案by alexander.polomodov

Your problem in updatedversion was getting collection of likes but not relation which you need to run $relation->save($like).

您在更新版本中的问题是获得喜欢的集合,但不是您需要运行的关系$relation->save($like)

See updated code below:

请参阅下面的更新代码:

public function LikePost($id, PostRepository $postRepo){
    $result = $postRepo->getById($id);
    $Like = new likeModel;
    error_log("5");
    $result->likes()->save($Like);
    error_log("6");
    $Like->status="success";
    return $Like;
}