I am using laravel 5.7, but i can't get current user id in __construct().
I also tried Auth:id(), but it also not working.
How to get current user id in constructor?
use Illuminate\Support\Facades\Auth;
class TestController extends Controller
{
public $id;
public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
$this->id = Auth::user()->id;
return $next($request);
});
dd($this->id);
}
}
Current output is null.
You can only access the session in the closure. Just refactor your code to this:
public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
$this->id = Auth::user()->id;
dd($this->id);
return $next($request);
});
}
You can now use the value $this->id in your controller methods.
In the example in your question, after you've set the value $this->id, you continue with the request. Since you try to access $this->id outside of the scope of the closure, it still is null in the datadump.
After return you will not go to next statement that's why it is not print.
If you want to use this in view then no need to pass in view you can simply access logged user id like this
{{Auth->user->id}}
if you wan to use this in controller make sure you are logged in.
Sometime session expired then you will not get user id
use Illuminate\Support\Facades\Auth;
class TestController extends Controller
{
public $id;
public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
$this->id = Auth::user()->id;
dd($this->id);
return $next($request);
});
}
}
The easiest solution is to create a middleware and call it later in the constructor.
php artisan make:middleware FoobarMiddleware
I recommend putting an alias in Kernel.php
protected $routeMiddleware = [
...
'foobar' => \App\Http\Middleware\FoobarMiddleware::class,
]
Constructor:
public function __construct()
{
$this->middleware('auth');
$this->middleware('foobar');
}
I recommend changing the focus of how you are creating everything
Related
What is the best way to declare a variable to be used in all the methods within my controllers and my models:
example .. I want to replace:
Auth::user()
by:
$this->user
What would be the best way to do it?
For Laravel 5.3.4+
Declare the property in your controller and then you can do it like this in its __construct method:
protected $user;
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->user = Auth::user();
return $next($request);
});
}
For versions below, you can just $this->user = Auth::user(); inside __construct.
Reference: https://laravel.com/docs/5.3/upgrade#5.3-session-in-constructors
If you attempt to set a user in your Controller.php's __construct method you will find it won't work.
This won't work:
public function __construct()
{
$this->user = auth()->check() ? auth()->user() : null;
}
This is by design, according Taylor, the framework's creator. He discourages setting your user in the base controller - but, it's up to you how you want to do things. There is a way around this. If you wanted $this->user to be accessible in every controller, you would add this to your Controller.php file:
protected function setUser()
{
$this->user = auth()->check() ? auth()->user() : null;
}
Then in your __construct method call it:
public function __construct()
{
$this->setUser();
}
Now, you can access this->user from any controller method. It will be null if not set, but if you are using Laravel's standard auth guard you shouldn't have much of a problem with unauthenticated users getting through.
Laravel Version: 5.6.*
PHP Version: 7.2.2
Database Driver & Version: Mysql 5.0.12
Description:
I need return logged user in contruct method
Steps To Reproduce:
I need return logged user in contruct method,
public function __construct(){
$this->menu = new Menu();
$this->menu->getEnabledMenu();
$this->categories = $this->
menu::with('children')->
where('parent_id','=',0)->
whereIn('id', [8,9,7])->
orderBy('position', 'asc')->
get();
}
i tried with $this->user->Auth::user()->id; but this doesn't work
i also tried this
https://laravel-news.com/controller-construct-session-changes-in-laravel-5-3
$this->middleware(function ($request, $next){
$this->user= Auth::user();
return $next($request);
});
but i I do not know how to access $this->user
please
i need help
sorry for my english
You need to define the $user property on your controller like:
class MyController {
// keep a reference to the authenticated user.
public $user;
public function __construct() {
$this->middleware(function ($request, $next){
$this->user = Auth::user();
return $next($request);
});
}
...
}
I want to use a terminable middleware for request logging:
<?php
namespace Illuminate\Session\Middleware;
use Closure;
use App\Helpers\Logger;
class LogRequest
{
public function handle($request, Closure $next)
{
return $next($request);
}
public function terminate($request, $response)
{
Logger::log($request, $response, $additionalInfo)
}
}
How can I pass the $additionalInfo from the controller to the middleware?
EDIT:
Unfortunately the additional info is generated in the controller. I therefore cannot hard code it in the route middleware function
Have you try to add to kernel.php:
protected $routeMiddleware = [
......
'LogRequest'=> \App\Http\Middleware\LogRequest::class
];
in the LogRequestMiddleware:
public function handle($request, Closure $next, $additionalInfo)
{
//here you have $additionalInfo
$request->attributes->add(["info" => $additionalInfo]);
return $next($request);
}
public function terminate($request, $response)
{
dd( $request->attributes);
}
And in controller:
public function __construct()
{
$additionalInfo = "test"
$this->middleware("LogRequest:$additionalInfo");
}
I think you can set some attribute to the request object in your controller while handling it, and the request object itself will be passed to terminate($request, $response) as the first parameter. Then you can extract whatever you set in your controller and use it.
Edited: You might be able to do this
Controller
$request->attributes->add(['additionalInfo' => 'additionalInfoValue']);
Middleware
public function terminate($request, $response)
{
$additionalInfo = $request->attributes('additionalInfo' => $additionalInfo);
Logger::log($request, $response, $additionalInfo)
}
I have Laravel 5.4 Base Controller which should share along children Controllers some common data depending on current Authenticated user.
I was Trying to get it like
public function __construct(ValidationFactory $validation)
{
$this->middleware(array('auth', 'lockscreen'));
var_dump(\Auth::user());
die;
}
this do not works.
private $userId;
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->userId = Auth::user()->id;
return $next($request);
});
}
I have this code
Controller.php
public function __construct()
{
$this->user = Auth::user();
view()->share('user', $this->user );
}
HomeController.php
public function __construct()
{
$this->middleware('auth');
parent::__construct();
}
It didn't work so I debug it with debugger and I saw that Auth::user() only return a user after finishing constructing.
i.e in HomeController#index() function
Any idea how to solve it ?
That used to work in laravel 5.2, however in laravel 5.3 you can no longer access session variables or the authenticated user in your controller's constructor. So they provided a work around that looks like this:
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->user = Auth::user();
return $next($request);
});
}
https://laravel.com/docs/5.3/upgrade#5.3-session-in-constructors
You can use auth()->user() or Auth::user() globally without creating any variables. You can use it even in views.
It's an auful idea to dublicate and store whole User object in a variable, session etc.