Reputation: 4539
Hello guys !
I'm working on an API that has a middleware authenticating the user with a unique ID. After making sure that this user exists, I want to send his database ID to the controller coming next, whichever it is.
Thanks !
Upvotes: 0
Views: 1186
Reputation: 39389
If you want the currently-authenticated user available in your application, just add it your base controller:
<?php namespace App\Http\Controllers;
use Illuminate\Contracts\Auth\Guard;
abstract class Controller {
protected $auth;
protected $currentUser;
public function __construct(Guard $auth)
{
$this->auth = $auth;
$this->currentUser = $this->auth->user();
}
}
Upvotes: 0
Reputation: 1012
Well, as long as you don't send that ID passing through the HTTP protocol, you should be fine since the user won't be able to tamper with the data.
That said, if you are using Laravel's built-in Auth
module, you should just do an Auth::user()
call at the other controller and it will give you the authenticated user.
If that isn't an option, you should create a function in the other controller that accepts $id
as a parameter. You can call that function from within the first controlling by constructing the second controller throug $secondController = App->make(SecondController)
and then $secondController->receiverFunction($id)
Upvotes: 0
Reputation: 1208
Is that a good idea ? Or should I get that ID somehow after the middleware finished ?
It depends on what you want to do and how you routes are declared. The routing is one of the first thing initialized by Laravel. You cannot pass parameter at run time (correct me if I'm wrong).
Plus, the controllers called after all midlewares has done their work.
I cannot garanty it's the more "beautiful" way to do this, but what i'm use to do is using Session::flash()
or Session::put()
when I want to pass parameters to my controllers at run time.
I use Session::flash()
if the parameter has a one request life time, and Session::put()
when I want the variable be more 'consistent' across the whole application.
I don't know if I am clear or not, tell me :)
Upvotes: 1