试着评论Laravel的照片

时间:2018-04-15 14:50:14

标签: php laravel laravel-5

您好我正在学习Laravel,我有一个图片库,我希望能够对每张照片发表评论 这是我的评论表:

 public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedinteger('user_id')->index();
            $table->unsignedinteger('photo_id')->index();
            $table->text('body',190);
            $table->timestamps();
        });
    }

这是我的照片表:

 public function up()
    {
        Schema::create('photos', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedinteger('user_id')->index();
            $table->string('title');
            $table->string('image');
            $table->timestamps();
        });
    }

这是照片模型:

protected $fillable = [
    'user_id','title','image'
];

public function user()
{
    return $this->belongsTo(User::class);
}
public function comments()
{
    return $this->hasMany(Comment::class);
}

这是评论模型:

protected $fillable = ['user_id','photo_id','body'];

public function user()
{
    return $this->belongsTo(User::class, 'user_id');
}
public function photo()
{
    return $this->belongsTo(Photo::class,'photo_id');
}

这是我的控制者:

   public function index()
    {
        // dd('here');
        $images = Photos::find($id);
        return View::make('detail')->with('images', $images);
        // return View::make('detail',compact($images,$comment));
        // $comment = Comment::all();
        // return view('detail',compact('comments'));
        // return view('detail');   
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request,$id)
    {
        // dd('test');
        $this->validate($request, [
            'photo_id' => 'required|exists:photos,id',
            'body' => 'required',
        ]);        
        $comment= Comment::create([
            'user_id'=>auth()->id(),
            'photo_id'=>request('photo_id'),
            'body'=>request('body')
        ]);
        return back();

    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Comment  $comment
     * @return \Illuminate\Http\Response
     */
    public function show(Comment $comment)
    {
        $comments = Comment::all();
        return view('detail',compact('comments'));
    }

我正在尝试使控制器工作,但这是不正确的,因为我仍然不完全理解雄辩的关系。请帮帮我。

1 个答案:

答案 0 :(得分:2)

您的表格和型号是正确的,您只需要通过id找到您的照片,然后将其保存为

$photo = Photo::find($id);

$photo->comments()->create([
    'user_id'=>auth()->id(),        
    'body'=>request('body')
]);

甚至你可以内联

Photo::find($id)->comments()->create([
    'user_id'=>auth()->id(),        
    'body'=>request('body')
]);