I have created a project which allows logged in users to created posts. The post table has a column called post_id
. The post_id has the value user id fetched from Session::get('id')
.
Now I want to fetch all posts associated with a loggedin user by using Post::where('post_id','=',Session::get('id');
Code Below
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
//use AppModelsUser;
use AppModelsPost;
use Session;
class PostController extends Controller
{
public function post(Request $request){
$posts = Post::where('post_id','=',Session::get('id'));
return view('dashboard',['posts' => $posts]);
}
}
in web.php
use AppHttpControllersPostController;
Route::get('/dashaboard',[PostController::class,'post']);
in dashboard view
@foreach ($posts as $post)
<tr>
<td>{{$post->post_title}}</td>
<td>{{$post->post_description}}</td>
</tr>
@endforeach
The error is
Undefined variable $posts
I tried to fetch logged in User’s posts. I want to fetch all posts.
3
Answers
So your setup is a little confusing. Let me break down how you should actually set this up.
In your
User
model, you should define a relationship for posts:In your
Post
model, you should define a relation for the user:In your posts database table, you’ll want a
user_id
integer column which will store the post user id.Once you’ve done this setup, you’ll be able to get all of the currently logged in users posts like this:
A bit correction to eloquent query that you are using.
And if the user has way to many posts, for example more than 25.
You can use pagination
https://laravel.com/docs/9.x/pagination#paginating-eloquent-results
Btw there are other way to get user id as long as this user is logged in
$user_id = auth()->user()->id;
$user_id = $request->user()->id;
$user_id = auth()->id();
For getting logged in user id
use Auth;
$user_id = Auth::user()->id;