Laravel 5: How to add Auth :: user () & # 8594; id via a constructor?
I can get the authenticated user ID like this:
Auth::user()->id = $id;
Great, it works ... but I have tons of methods that need it and I want an easier way to add it to the class as a whole, so I can just reference the $ id in every method. I was thinking about putting it in the constructor, but since Auth :: user is static, I'm making a mess and don't know how.
Many thanks for your help!
source to share
You can use Auth :: user () throughout your application. It doesn't matter where you are. But in response to your question, you can use the Controller class present in your controllers folder. Add a constructor there and link to the user ID.
<?php namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesCommands;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
/* Don't forget to add the reference to Auth */
use Auth;
abstract class Controller extends BaseController {
use DispatchesCommands, ValidatesRequests;
function __construct() {
$this->userID = Auth::user()?Auth::user()->id:null;
}
}
Then in any method of any controller, you can use the $ this-> userID variable.
source to share
Instead of using Facade, you can enter a contract for the authentication class and then set the user id on your controller. Similar to @rotvulpix, you can put this in your base controller so that all child controllers have access to the user id as well.
<?php
namespace App\Http\Controllers;
use Illuminate\Contracts\Auth\Guard;
class FooController extends Controller
{
/**
* The authenticated user ID.
*
* @var int
*/
protected $userId;
/**
* Construct the controller.
*
* @param \Illuminate\Contracts\Auth\Guard $auth
* @return void
*/
public function __construct(Guard $auth)
{
$this->userId = $auth->id();
}
}
The defender has a method id()
that returns void
if the user is not logged in, which is a little easier than going through user()->id
.
source to share
Laravel> = 5.3
you cannot access the session or authenticated user in your controller constructor as the middleware has not started yet.
Alternatively, you can define Closure-based middleware directly in your controller constructor. Make sure your application is running Laravel 5.3.4
or higher before using this function :
class UserController extends Controller {
protected $userId;
public function __construct() {
$this->middleware(function (Request $request, $next) {
if (!\Auth::check()) {
return redirect('/login');
}
$this->userId = \Auth::id(); // you can access user id here
return $next($request);
});
}
}
source to share