Use Auth in construct method - laravel

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);
});
}
...
}

Related

How do I validate User role on Laravel 5.8s Built in Authentication?

I've a User Role column on my User's table.
stands for Super Admin,
stands for other users
I've checked a lot of Laravel Tutorials and none of them has helped me about solving this issue.
I've found ways like replacing the whole Laravel's Login Controller and replacing Authenticate Users trait with ours own. I want to solve my problem with minimal code change. Is it possible?
How do I implement it with minimal code changes in this Trait method?
public function login(Request $request)
{
$this->validateLogin($request);
if (method_exists($this, 'hasTooManyLoginAttempts') &&
$this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
You could do something as supersimple as adding a isSuperAdmin function to the User model. After logging in you just call this function on the user whenever you need to check.
In model User.php
public function isSuperAdmin()
{
return $this->user_role == 1;
}
Then you could also make a middleware that's using this function.
php artisan make:middleware SuperAdmin
In the handle function of this middleware (app/http/middleware/SuperAdmin.php):
public function handle($request, Closure $next)
{
if (Auth::check() && Auth::user()->isSuperAdmin()) {
return $next($request);
}
return redirect('some-route-for-unauthorized-users');
}
Then in your routes (probably web.php), you can use this middleware to protect routes:
Route::group(['middleware' => ['auth', 'superadmin']], function () {
... put protected routes here ...
});
Solution
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware('guest')->except('logout');
}
protected function credentials(Request $request)
{
$credentials = $request->only($this->username(), 'password');
$credentials['role'] = '1';
return $credentials;
}

How to get current user id in constructor in laravel?

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

Declare a variable to be used in all methods Laravel

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.

Get User in Laravel 5.4 Controller constructor

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

Making global user variable in laravel 5.3

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.

Resources