Search code examples
phplaravelgetfetchfind

Laravel: How to fetch all logged in User Posts using Session variable


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 App\Http\Controllers;

use Illuminate\Http\Request;
//use App\Models\User;
use App\Models\Post;
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 App\Http\Controllers\PostController;

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.


Solution

  • A bit correction to eloquent query that you are using.

    $user_id = Session::get('id');
    
    // change post_id into user_id
    // and add ->get() to fetch all posts related to user_id
    $posts = Post::where('user_id','=', $user_id)->get();
    

    And if the user has way to many posts, for example more than 25.
    You can use pagination

    $perPage = 25;
    $posts = Post::where('user_id','=', $user_id)->paginate($perPage);
    

    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();