Get User in Laravel 5.4 Controller constructor - laravel-5

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

Related

laravel 6 redirect back to page after login using socialite package [duplicate]

I have a page with a some content on it and a comments section. Comments can only be left by users who are signed in so I have added a login form to the page for users to sign in with (this only shows if they are not already logged in).
The problem I have is that when the user signs in they get redirected back to the home page and not the page they were previously on.
I have not changed the login method from the out of the box set-up.
Can anyone suggest a simple way to set the redirect url. My thoughts are that it would be good to be able to set it in the form.
Solution for laravel 5.3:
In loginController overwrite the showLoginForm() function as this one:
public function showLoginForm()
{
if(!session()->has('url.intended'))
{
session(['url.intended' => url()->previous()]);
}
return view('auth.login');
}
It will set the "url.intended" session variable, that is the one that laravel uses to look for the page which you want to be redirected after the login, with the previous url.
It also checks if the variable has been set, in order to avoid the variable to be set with the login url if the user submit the form with an error.
For Laravel 5.5, following code worked for me by just updating LoginController.php
public function showLoginForm()
{
session(['link' => url()->previous()]);
return view('auth.login');
}
protected function authenticated(Request $request, $user)
{
return redirect(session('link'));
}
Please use redirect()->intended() instead in Laravel 5.1
You can also see more about it here: http://laravel.com/docs/5.1/authentication
For Laravel 5.3
inside App/Http/Controllers/Auth/LoginController
add this line to the __construct() function
$this->redirectTo = url()->previous();
So the full code will be
public function __construct()
{
$this->redirectTo = url()->previous();
$this->middleware('guest', ['except' => 'logout']);
}
It works like a charm for me i'm using laravel 5.3.30
For Laravel 5.4, following code worked for me by just updating LoginController.php
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\URL;
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
Session::put('backUrl', URL::previous());
}
public function redirectTo()
{
return Session::get('backUrl') ? Session::get('backUrl') : $this->redirectTo;
}
The Laravel 5.6, When user insert wrong credentials then login page will reload and session(['link' => url()->previous()]); will take login URL in link variable. So the user will redirect to a login page again or redirect to /home if login success. So to avoid these below code working for me! After that no matter how much time user insert wrong credentials he will redirect after login to exactly where he was before login page.
Update or overwrite public function showLoginForm() in LoginController.
public function showLoginForm()
{
if (session('link')) {
$myPath = session('link');
$loginPath = url('/login');
$previous = url()->previous();
if ($previous = $loginPath) {
session(['link' => $myPath]);
}
else{
session(['link' => $previous]);
}
}
else{
session(['link' => url()->previous()]);
}
return view('auth.login');
}
Also, Update or Overwrite protected function authenticated(Request $request, $user) in LoginController.
protected function authenticated(Request $request, $user)
{
return redirect(session('link'));
}
If you want to redirect always to /home except for those pages with comments, then you should overwrite your redirectTo method in your LoginController:
public function redirectTo()
{
return session('url.intended') ?? $this->redirectTo;
}
On all pages where you want to remain on the site, you should store the url for one request in the session:
public function show(Category $category, Project $project){
// ...
session()->flash('url.intended' , '/' . request()->path());
}
Redirect to login with the current's page url as a query string:
login
In your LoginController check if exists and save the query string in session then redirect to the url after login
public function __construct() {
parent::__construct();
if ( \request()->get( 'redirect_to' ) ) {
session()->put( 'redirect.url', \request()->get( 'redirect_to' ) );
}
$this->middleware( 'guest' )->except( 'logout' );
}
protected function authenticated(Request $request, $user) {
if(session()->has('redirect.url') {
return redirect( session()->get( 'redirect.url' ) );
}
}
Look into laravel cheat sheet
and use:
URL::previous();
to go to the previous page.
Laravel 5
(maybe 6 also, not tested, if someone knows it please update the answer)
add this to LoginController:
protected function redirectTo(){
return url()->previous();
}
Note: if present the field $redirectTo , remove it
in your RedirectIfAuthenticated.php change this code
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect()->intended('/contactus');
}
return $next($request);
}
please notice to :
return redirect()->intended('/contactus');
Inside your template file you can just use:
{{ url()->previous() }}
To redirect from the controller you should use
return redirect()->back();
or Just
return back();
use Illuminate\Support\Facades\Redirect;
public function Show_Login_Form()
{
$back = Session::put('url_back',url()->previous());
$current = url()->current();
if(Session::get('user_id'))
{
if ($back == $current) { // don't back Login Form
return Redirect::to('home');
}
elseif (Session::has('url_back')) {
return Redirect::to('home');
}
else{
return redirect()->back();
}
}
else{
if ($back == $current) {
return Redirect::to('home');
}
else{
Session::put('url_back',url()->previous());
}
return view('account.customer-account.login');
}
}
public function signin_user(Request $request) // Login post
{
$username = $request->input_username_login;
$password = md5($request->input_password_login);
$result = DB::table('tbl_user')
->where([['user_email',$username],['user_password',$password]])
->orWhere([['user_phone',$username],['user_password',$password]])
->first();
if($result){
Session::put('user_id', $result->user_id );
Session::put('user_name', $result->user_name);
Session::put('user_username', $result->user_username);
Session::put('user_avatar', $result->user_avatar);
return Redirect::to(Session::get('url_back')); // Back page after login
} else {
Session::put('message_box', 'Error !!!');
return redirect()->back();
}
}
You can use redirect back with Laravel 5:
<?php namespace App\Http\Controllers;
use Redirect;
class SomeController extends Controller {
public function some_method() {
return Redirect::back()
}
}
Use Thss
return Redirect::back('back-url')

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

Use Auth in construct method

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

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