Home > Software engineering >  Laravel: How to fetch all logged in User Posts using Session variable
Laravel: How to fetch all logged in User Posts using Session variable

Time:02-01

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.

CodePudding user response:

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:

public function posts() {
  return $this->hasMany(Post::class);
}

In your Post model, you should define a relation for the user:

public function user() {
  return $this->belongsTo(User::class);
}

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:

  public function post(Request $request){
         $posts = $request->user()->posts;
         return view('dashboard',['posts' => $posts]);
   }

CodePudding user response:

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

  • Related