i have post table and i have comment table i have made them with laravel i made a IndexController and it has a method that returns all of my posts by their title; i also return and compact comment of each post and show them under each post content but i have to pass the post id to comment table by myself for example i have a post with id=7 and i have to pass the 7 to post_id column of comment table i have to write a query something like this
select id from posts where title=$title
with this query i want to select post id by post title and pass it to post_id in my comment table
this my index controller
public function single($title)
{
$posts = Post::where('title', $title)->get();
$comments = Comment::where([
['post_id', 7],
['verify',1]
])->orderBy('id', 'desc')->get();
return view('main.single', compact('posts', 'comments'));
}
this is comment controller
public function store(Request $request)
{
Comment::create([
'post_id' => $request['post_id'],
'user_id' => Auth::user()->id,
'message' => $request['message'],
]);
}
and also this my single blade file code
@foreach($comments as $comment)
<div >
<div >
<div>
<p >{{$comment->user->first_name.' '.$comment->user->last_name}}
<br>
<span >{{$comment->created_at}}</span>
</p>
</div>
<div >
</div>
<div>
{{$comment->message}}
</div>
</div>
</div>
@endforeach
and also i use laravel 8
CodePudding user response:
You can do the following if you don't want to pass by yourself, assuming your relationships are correct. If not, feel free to include them in your current question, and I can help with those too.
public function single($title)
{
$post = Post::with(['comments' => function ($query) {
$query->where('verify', 1)->orderBy('id', 'desc');
}])->where('title', $title)->first();
return view('main.single', compact('post'));
}
This will allow you to pass just a post to your blade view.
Now instead of
@foreach($comments as $comment)
You can
@foreach($post->comments as $comment)
