4

I'm using Laravel 5.5 I have a 'Post' Model. In that model I want to use a Route Parameter (say userId).. I have this id in Post Controller.

public function getPosts($userId)
{      
    $posts = Post::latest()->paginate(8);
    return Response::json($posts);
}

I want to use the $userId in the Post Model to get some more information. How do I access this parameter from the Post model? Should I use session to store the userId value and try to use it? Is there any other way?

Sk Golam Saroar
  • 376
  • 1
  • 5
  • 20

3 Answers3

11

You can use the request() helper:

// Get a specific route parameter 
request()->route()->parameter('userId')

// Get all route parameters 
request()->route()->parameters()

Say you have a function on a Post model:

// Post.php

public function doSomething()
{
    if (request()->route()->parameter('userId') === 1) {
        return 'some value';
    }
    return 'another value';
}
alexeydemin
  • 2,672
  • 3
  • 27
  • 26
2

You can do this:

request()->route('userId')
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
2

The accepted answer is completely correct, but I just want to add one thing.

Note: if You are using:

request()->route()->parameter('userId');

You might actually get the whole User object, not just the ID, since Laravel can automatically find the entry in Your User table and inject it into the request.

If that happens, You might get some nasty, unlogicall errors, but the solution is easy: Just add the ->id to that request line (or whatever the name of Your ID attribute is). Like this:

request()->route()->parameter('userId')->id;
Aleksandar
  • 3,558
  • 1
  • 39
  • 42