Hello I am learning Laravel and I have an image gallery and I want to be able to comment on each photo This is my comments table:
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();
});
}
This is my photos table:
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();
});
}
this is the photos model:
protected $fillable = [
'user_id','title','image'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
and this is the comment model:
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');
}
And this is my controller:
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'));
}
I am trying to make the controller work but it is not correct because I still do not understand Eloquent relationships fully. Please help me.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire