I made a blog where you can CRUD articles and post comments. Everything is fine and working good.
I just want to make Laravel to do the magic when the User posts a comment to an article and instead of hard-coding article_id
and user_id
.
Comment::create([
'body' => request('body'),
'article_id' => $article->id,
'user_id' => Auth::User()->id]
);
Is it possible to use Laravel's Eloquent relationships to chain up some functions/methods and simplify it a little bit?
Depends. If user_id
and article_id
are both nullable
(which I doubt, but let's assume they are) you can use Eloquent like this:
$user = Auth::User()->id;
$article = Article::find($request('article_id'));
$comment = Comment::create(['body' => $request('body')]);
$comment->article()->associate($article);
$comment->user()->associate($user);
Otherwise, another method that can improve it a little bit is something like this:
$article = Article::find('article_id');
$article->comments()->save(new Comment([
'body' => request('body');
'user_id' => Auth::User()->id;
]);
The same can be done for the user too.