Laravel After Logging in is going to / Route - laravel

This is mine LoginController
protected $redirectTo;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
if(Auth::check() && Auth::user()->role->id == 1){
$this->redirectTo=route('admin.dashboard');
}
else{
$this->redirectTo=route('user.dashboard');
}
$this->middleware('guest')->except('logout');
}
}
Here is mine web.php
Route::get('/', function () {
return view('welcome');
})->name('home');
Auth::routes();
I don't know Why after Successfully logging in its going to / route i want to send it to another route which after logging in i manually Enter the route i successfully viewed that route if i am logged in its not going to show but how can i manage after logging in route

You are doing it wrong. You shouldn't put such code into controller constructor because it won't probably work.
Instead in your controller you should define custom redirectTo method:
protected function redirectTo()
{
if(Auth::check() && Auth::user()->role->id == 1) {
return route('admin.dashboard');
}
return $this->redirectTo=route('user.dashboard');
}
This should work because in Illuminate/Foundation/Auth/RedirectsUsers.php trait there is method:
public function redirectPath()
{
if (method_exists($this, 'redirectTo')) {
return $this->redirectTo();
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
}
defined that is used later in LoginController by default when user was succesfully logged.

Related

Laravel 5.8 | Redirect to previous URL after login/register/reset password

i have in my LoginController function:
protected $redirectTo = '/';
protected function authenticated(Request $request, $user) {
if ($user->is_admin == true) {
return redirect('/home');
}
return redirect('/');
}
and in RedirectIfAuthenticated middleware:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/');
}
if (Auth::guard($guard)->check() && Auth::user()->is_admin == true) {
return redirect('/home');
}
return $next($request);
}
I tried too use in both places:
return redirect()->intended();
and
return redirect()->back();
but every time it brings me under
localhost/
Focusing on the user part, I'm trying to do a login redirect to the previous URL. Could someone please help me to correct this redirect?
Thank you
After I changed this
protected $redirectTo = '/';
to this
protected function redirectTo()
{
return redirect()->back();
}
protected function authenticated(Request $request, $user) {
if ($user->is_admin == true) {
return redirect('/home');
}
return redirect()->back();
}
i got error:
The localhost page caused too many redirects.
Looking at the docs:
If the redirect path needs custom generation logic you may define a
redirectTo method instead of a redirectTo property
So instead of protected $redirectTo = '/';
Try
protected function redirectTo()
{
return url()->previous();
}

Laravel: How the best way for redirect a default laravel user to admin page if user is admin or to user page if user is not admin?

The User model has an isAdmin() function to check if the user is an administrator. What to do next?
The best way is to use default laravel LoginController located under App\Http\Controllers\Auth\LoginController.
In that controller you can override authenticated method that is injected from AuthenticatesUsers trait, by simply adding that method in LoginController:
* #param Request $request
* #param $user
*/
protected function authenticated(Request $request, $user)
{
if ($user->isAdmin()) {
return redirect(route('admin-dashboard'));
//redirect to desired place since user is admin.
}
}
Best practique is whit roles, and you add role on your Routes::middleware,
Route::group(['middleware' => ['auth', 'roles:admin']], function () {
//Your routes
});
Kernel.php
'roles' => Middleware\CheckRole::class,
Create middleware
namespace App\Http\Middleware;
use Closure;
class CheckRole
{
public function handle($request, Closure $next, ...$role)
{
if ($request->user()->hasAnyRole($role)) {
return $next($request);
}
return redirect(route('hour'));
}
}
create function on User model
public function authorizeRole($role)
{
if ($this->hasAnyRole($role)) {
return true;
}
return abort(401, 'Unauthorized.');
}
public function hasAnyRole($roles)
{
if (is_array($roles)) {
foreach ($roles as $role) {
if ($this->hasRole($role)) {
return true;
}
}
} else {
if ($this->hasRole($roles)) {
return true;
}
}
return false;
}
public function hasRole($role)
{
if ($this->role()->where('name', $role)->first()) {
return true;
}
return false;
}
public function role()
{
return $this->belongsTo('App\Role')->withDefault();
}
And Role model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function user()
{
return $this->hasMany('App\User');
}
}
Is more code, but best way for this action

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

Laravel fails to redirect when specifying URL

I want Laravel to redirect to '/dashboard' instead, Laravel keeps taking me to '/' after login.
LoginController.php
public function redirectPath()
{
return '/dasboard';
}
Middleware
if (Auth::guard($guard)->check())
{
return redirect()->intended('/dashboard');
}
protected function authenticated()
{
return redirect('/home');
}

how can i redirect user , seller and admin to their panel in laravel 5

i have level column in user table , i wanna redirect to their panel in laravel after login but i dont know where check and redirect user???
i try to login safty
Can this code be correct?
protected function authenticated(Request $request, $user)
{
if(auth()->user()->isAdmin())
{
return redirect('/admin/panel');
} elseif(auth()->user()->isWriter())
{
return redirect('/writer/panel');
}
return redirect('/user/panel');
}
Overwrite redirectPath() method to your LoginController.
class LoginController extends Controller
{
use AuthenticatesUsers;
public function redirectPath()
{
if (auth()->user()->isAdmin())
{
return '/admin/panel';
}
elseif (auth()->user()->isWriter())
{
return '/writer/panel';
}
return '/user/panel';
}
}
In LoginController that uses Illuminate\Foundation\Auth\AuthenticatesUsers trait for authentication you must override the redirectTo() method and write your own logic. so you must something like this code:
protected function redirectTo(){
$user = User::whereId(Auth::id())->first();
if(isset($user)){
if($user->role == 'admin'){
return '/admin/panel'; //path to admin panel
}elseif($user->role == 'writer'){
return '/writer/panle'; //path to writer panel
}
}
return '/';
}

Resources