Auth::guard('user')->user() is null in Laravel 5.3 - laravel

I'm trying to pass to all templates current user object like this:
class Controller extends BaseController
{
public function __construct()
{
view()->share('usr', Auth::guard('user'));
}
}
Every controller is extended by Controller. But if i try to dump Auth::guard('user')->user() Laravel returns null, although I am logged in. Moreover when i pass this variable into template, {{ $usr->user() }} returns current user. What I've done wrong?
my config/auth.php
'defaults' => [
'guard' => 'user',
'passwords' => 'users',
],
'guards' => [
'user' => [
'driver' => 'session',
'provider' => 'user',
],
],
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
],
Kernel.php
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
//\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
my own function to log in:
public function authorizes(Request $request)
{
$this->validate($request, [
'login' => 'required|max:50',
'password' => 'required|max:50'
]);
$credentials = $request->only(['login', 'password' ]);
$remember = $request->get('remember', false) == 1 ? true : false;
if ($this->guard->attempt( $credentials, $remember)) {
$user = $this->guard->user();
$user->last_login = date('Y-m-d H:i:s');
$user->save();
return redirect()->route( 'homepage' )->withSuccess(trans('app.login.success'));
}
return redirect()->back()->withErrors(trans('app.wrong.credentials'));
}

In Laravel 5.3 you should change your controller constructor like so to make this work (assuming you use at least Laravel 5.3.4):
public function __construct()
{
$this->middleware(function ($request, $next) {
view()->share('usr', Auth::guard('user'));
return $next($request);
});
}
You can see this change described in Upgrade guide:
In previous versions of Laravel, you could access session variables or
the authenticated user in your controller's constructor. This was
never intended to be an explicit feature of the framework. In Laravel
5.3, you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.
As an alternative, you may define a Closure based middleware directly
in your controller's constructor. Before using this feature, make sure
that your application is running Laravel 5.3.4

Try to do this:
view()->share('usr', Auth::user());
Or this:
view()->share('usr', auth()->user());

Frist check if user is logged or not, then share the current user as:
public function __construct()
{
if (auth()->check()) {
$this->currentUser = auth()->user();
View::share('currentUser', $this->currentUser);
} else {
// you can redirect the user to login page.
}
}

In your case there are two things to consider
To get actual user model you should do Auth::guard('user')->user()
Auth::user() is actually not yet initialized when view()->share() is called, see https://github.com/laravel/framework/issues/6130
Therefore you could rather use view composer. In boot method of your AppServiceProvider add:
\View::composer('*', function ($view) {
$view->with('usr', \Auth::guard('user')->user());
});

Related

different login routes and login views for student and admin

Every laravel newbie struggles with multi auth, I am no exception
I am trying to make student management system. There will two different routs for admin admin/login and for student student/login.
The student can't register itself, but he will be registered by admin.
So a student has only access to student/dashboard, registration of students will be done by the admin on admin/dashboard.
Below is the detail what I have already done:
created migration for both admin and student.
created guard for both admin and student.
modified login controller and added adminLogin and studentLogin methods.
modified RedirectIfAuthenticated middleware
Config/auth.php
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'students' => [
'driver' => 'session',
'provider' => 'students',
],
'web-admin'=>[
'driver'=>'session',
'provider'=>'admin',
],
'api' => [
'driver' => 'token',
'provider' => 'students',
'hash' => false,
],
],
'providers' => [
'students' => [
'driver' => 'eloquent',
'model' => App\Student::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
'passwords' => [
'students' => [
'provider' => 'students',
'table' => 'password_resets',
'expire' => 60,
],
'admin' => [
'provider' => 'admin',
'table' => 'password_resets',
'expire' => 60,
],
],
LoginController.php
lass LoginController extends Controller
{
use AuthenticatesUsers;
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('guest:web-admin')->except('logout');
$this->middleware('guest:students')->except('logout');
}
public function showAdminLoginForm()
{
return view('admin.login', ['url' => 'admin']);
}
public function adminLogin(Request $request)
{
$this->validate($request, [
'admin_id' => 'required',
'password' => 'required|min:8'
]);
if (Auth::guard('admin')->attempt(['admin_id' => $request->adminid, 'password' => $request->password], $request->get('remember'))) {
return redirect()->intended('/admin/dashboard');
}
return back()->withInput($request->only('admin_id', 'remember'));
}
public function showStudentLoginForm()
{
return view('student.login', ['url' => 'student']);
}
public function studentLogin(Request $request)
{
$this->validate($request, [
'roll_no' => 'required',
'password' => 'required|min:8'
]);
if (Auth::guard('writer')->attempt(['roll_no' => $request->roll_no, 'password' => $request->password], $request->get('remember'))) {
return redirect()->intended('/student/dashboard');
}
return back()->withInput($request->only('roll_no', 'remember'));
}
}
RedirectAuthenticated.php
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if('web_admin'==='$guard'){
return redirect('/admin/dashboard');
}
return redirect('/admin/login');
}
if (Auth::guard($guard)->check()) {
if('students'==='$guard'){
return redirect('/student/dashboard');
}
return redirect('/student/login');
}
return $next($request);
}
}
I have created two folders in the view, student and admin. They both have two files. login.blade.php and dashboard.blade.php
What laravel does it it shows login, and register under auth folder.
I want to give two routes one for /admin/login which return admin.login view.
Same for student /student/login which return student.login view.
I want to remove /register route and make the link to available on admin dashboard , there will be no admin register link.
Also restrict the user from accessing admin area.
**I don't want the whole code, just help me steps and way that I should follow or changes I have to make **
Finally I solved it. I didn't use php artisan make:auth, instead I did it from scratch. Created a fresh project, deleted User.php and the migration.
Created models Student.php and Admin.php along with migrations and controllers.
php artisan make:model Student -mc
php artisan make:model Admin -mc
After than I created guards, I deleted default guard (I don't know It was right to do so, but I felt that if there is no need of default guard and also it was using users table so I deleted).
Here is config/auth.php
'guards' => [
'student'=>[
'driver'=>'session',
'provider'=>'students'
],
'admin'=>[
'driver'=>'session',
'provider'=>'admins'
],
],
'providers' => [
'students'=>[
'driver'=>'eloquent',
'model'=>App\Student::class,
],
'admins'=>[
'driver'=>'eloquent',
'model'=>App\Admin::class,
]
So I have two guards student and admin.
Here is the admin model Admin.php
class Admin extends Authenticatable
{
use Notifiable;
protected $fillable = [
'firstname', 'lastname','admin_id', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
and model Student Student.php
class Student extends Authenticatable
{
use Notifiable;
protected $fillable = [
'firstname', 'lastname','admin_id', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
After this I modified AdminController.php
class AdminsController extends Controller
{
use AuthenticatesUsers;
protected $guard = 'admin';
public function showLogin(){
return view('admin.login');
}
public function dashboard(){
return view('admin.dashboard');
}
public function login(Request $request){
$this->validate($request,[
'admin_id' => 'required',
'password'=>'required|min:8',
]);
if(Auth::guard('admin')->attempt(['admin_id'=>$request['admin_id'], 'password'=>$request['password']])){
return redirect('admin/dashboard');
}
return redirect('/admin');
}
}
Then I created routes Web.php
Route::get('/', function () {
return view('welcome');
});
Route::get('/admin','AdminsController#showLogin');
Route::get('/student','StudentsController#showLogin');
Route::get('/admin/dashboard','AdminsController#dashboard');
Route::get('/student','StudentsController#showLogin');
Route::post('/admin/login','AdminsController#login');
Route::post('/student/login','StudentsController#login');
Now, at this time login works. I still need to do a lot. If any suggestion, I welcome that, please comment below.

How to create multi auth in laravel 5.6?

I used to be for laravel 5.5 and earlier than https://github.com/Hesto/multi-auth .
But this repository don't update for laravel 5.6.
How to create multi auth in Laravel 5.6?
After lots of digging and lots of questions & answers I have finally managed to work Laravel 5.6 Multi Auth with two table, So I'm writing Answer of my own Question.
How to implement Multi Auth in Larvel
As Mentioned above.
Two table admin and users
Laravel 5.2 has a new artisan command.
php artisan make:auth
it will generate basic login/register route, view and controller for user table.
Make a admin table as users table for simplicity.
Controller For Admin
app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController
(note: I just copied these files from app/Http/Controllers/Auth/AuthController here)
config/auth.php
//Authenticating guards
'guards' => [
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
//User Providers
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
]
],
//Resetting Password
'passwords' => [
'clients' => [
'provider' => 'client',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
route.php
Route::group(['middleware' => ['web']], function () {
//Login Routes...
Route::get('/admin/login','AdminAuth\AuthController#showLoginForm');
Route::post('/admin/login','AdminAuth\AuthController#login');
Route::get('/admin/logout','AdminAuth\AuthController#logout');
// Registration Routes...
Route::get('admin/register', 'AdminAuth\AuthController#showRegistrationForm');
Route::post('admin/register', 'AdminAuth\AuthController#register');
Route::get('/admin', 'AdminController#index');
});
AdminAuth/AuthController.php
Add two methods and specify $redirectTo and $guard
protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
it will help you to open another login form for admin
creating a middleware for admin
class RedirectIfNotAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = 'admin')
{
if (!Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}
register middleware in kernel.php
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];
use this middleware in AdminController
e.g.,
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class AdminController extends Controller
{
public function __construct(){
$this->middleware('admin');
}
public function index(){
return view('admin.dashboard');
}
}
That's all needed to make it working and also to get json of authenticated admin use
Auth::guard('admin')->user()
We can access authenticated user directly using
Auth::user()
but if you have two authentication table then you have to use
Auth::guard('guard_name')->user()
for logout
Auth::guard('guard_name')->user()->logout()
for authenticated user json
Auth::guard('guard_name')->user()

creating a custom authentication system in laravel

How can I build an authentication system for customer?
I have used laravel built in authentication system for my admin panel where built in user model and users table already used.
Now I want to build another authentication system for my customer where customer model and customers table will be used.
How can I do this in laravel 5.2 ?
How to implement Multi Auth in Larvel 5.2
As Mentioned above. Two table admin and users
Laravel 5.2 has a new artisan command.
php artisan make:auth
it will generate basic login/register route, view and controller for user table.
Make a admin table as users table for simplicity.
Controller For Admin
app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController
(note: I just copied these files from app/Http/Controllers/Auth/AuthController here)
config/auth.php
//Authenticating guards
'guards' => [
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
//User Providers
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
]
],
//Resetting Password
'passwords' => [
'clients' => [
'provider' => 'client',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
route.php
Route::group(['middleware' => ['web']], function () {
//Login Routes...
Route::get('/admin/login','AdminAuth\AuthController#showLoginForm');
Route::post('/admin/login','AdminAuth\AuthController#login');
Route::get('/admin/logout','AdminAuth\AuthController#logout');
// Registration Routes...
Route::get('admin/register', 'AdminAuth\AuthController#showRegistrationForm');
Route::post('admin/register', 'AdminAuth\AuthController#register');
Route::get('/admin', 'AdminController#index');
});
AdminAuth/AuthController.php
Add two methods and specify $redirectTo and $guard
protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
it will help you to open another login form for admin
creating a middleware for admin
class RedirectIfNotAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = 'admin')
{
if (!Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}
register middleware in kernel.php
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];
use this middleware in AdminController e.g.,
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class AdminController extends Controller
{
public function __construct(){
$this->middleware('admin');
}
public function index(){
return view('admin.dashboard');
}
}
That's all needed to make it working and also to get json of authenticated admin use
Auth::guard('admin')->user()
Edit - 1
We can access authenticated user directly using
Auth::user() but if you have two authentication table then you have to use
Auth::guard('guard_name')->user()
for logout
Auth::guard('guard_name')->user()->logout()
for authenticated user json
Auth::guard('guard_name')->user()

How to Create Multi Auth in Laravel 5.2

I have made multi auth but i have problem with final code. I have code like this
php artisan make:auth
it will generate basic login/register route, view and controller for user table.
Make a admin table as users table for simplicity.
Controller For Admin
app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController
(note: I just copied these files from app/Http/Controllers/Auth/AuthController here)
config/auth.php
//Authenticating guards
'guards' => [
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
//User Providers
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
]
],
//Resetting Password
'passwords' => [
'clients' => [
'provider' => 'client',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
route.php
Route::group(['middleware' => ['web']], function () {
//Login Routes...
Route::get('/admin/login','AdminAuth\AuthController#showLoginForm');
Route::post('/admin/login','AdminAuth\AuthController#login');
Route::get('/admin/logout','AdminAuth\AuthController#logout');
// Registration Routes...
Route::get('admin/register', 'AdminAuth\AuthController#showRegistrationForm');
Route::post('admin/register', 'AdminAuth\AuthController#register');
Route::get('/admin', 'AdminController#index');
});
AdminAuth/AuthController.php
Add two methods and specify $redirectTo and $guard
protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
it will help you to open another login form for admin
creating a middleware for admin
class RedirectIfNotAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = 'admin')
{
if (!Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}
register middleware in kernel.php
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];
use this middleware in AdminController e.g.,
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class AdminController extends Controller
{
public function __construct(){
$this->middleware('admin');
}
public function index(){
return view('admin.dashboard');
}
}
And what does this code mean Auth::guard('admin')->user() ? And where must i type that code?
And what does this code mean Auth::guard('admin')->user() ?
In simple word, Auth::guard('admin')->user() is used when you need to get details of logged in user. But, in multi auth system, there can be two logged in users (admin/client). So you need to specify that which user you want to get. So by guard('admin'), you tell to get user from admin table.
Where must i type that code?
As from answer, you can understand that where must you use it. But still I can explain with example. Suppose there are multiple admins. Each can approve users request (like post/comments etc). So when an admin approve any request, then to insert id of that admin into approved_by column of post, you must use this line.

Call to a member function set() on null

I am trying to use oauth for google in laravel 5 but i am getting the error. Can any one help me to sort out this problem.
Followings are my files please check out
.env
GOOGLE_ID = 'mygoogleId'
GOOGLE_SECRET = 'mysecretID'
GOOGLE_REDIRECT = http://localhost:8090/users
services.php
'google' => [
'client_id' => env('GOOGLE_ID'),
'client_secret' => env('GOOGLE_SECRET'),
'redirect' => env('GOOGLE_REDIRECT'),
],
AuthController
public function redirectToProvider() {
return Socialite::driver('google')->redirect();
}
public function handleProviderCallback() {
$user = Socialite::driver('google')->user();
console.log($user);
}
routes.php
Route::get('google', 'Auth\AuthController#redirectToProvider');
Route::get('google/callback', 'Auth\AuthController#handleProviderCallback');
//I have set the providers and aliases in app.php.
Here is the code where i am getting an error
//on set() method
public function redirect()
{
$state = str::random(40);
if ($this->usesState()) {
$this->request->getSession()->set('state', $state);
}
return new RedirectResponse($this->getAuthUrl($state));
}
Thanks in advance..
Hey If you are using laravel 5.2, this is worked for me.
Put your controllers in 'web' middleware. like,
Route::group(['middleware' => 'web'], function() {
Route::get('google', 'Auth\AuthController#redirectToProvider');
Route::get('google/callback', 'Auth\AuthController#handleProviderCallback');
});
and Make sure Kernel file has middleware classes registered.
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\Perkweb\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Perkweb\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];

Resources