redirecTo() method in laravel not working - php

I have been trying to redirect a user after login, there are two links that should be redirected to when a certain condition is fulfilled.
protected function redirectTo(){
$userRole = User::findOrFail(Auth::id());
// dd($userRole->roles);
if($userRole->roles == 'admin'){
return 'admin/controlpanel';
}
elseif ($userRole->roles == 'participant') {
return 'student/profile';
}
}
I created this function to redirect but it still redirect to '/home'. Then I read over here and on git that I also had to the modify RedirectIfAuthenticated model in the middleware, I did this
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use App\User;
class RedirectIfAuthenticated
{
/**
* 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 = null)
{
if (Auth::guard($guard)->check()) {
return self::redirectTo();
}
return $next($request);
}
protected function redirectTo(){
$userRole = User::findOrFail(Auth::id());
if($userRole->roles == 'admin'){
return 'admin/controlpanel';
}
if ($userRole->roles == 'participant') {
return 'student/profile';
}
}
}
but is still keeps giving me this error in my previous question
here
I reverted to my previous git commit, then coded step by step till I discovered it was coming from the middleware I modified...

use redirect helper like this: return redirect('admin/controlpanel');

Related

Call to a member function setCookie() on null - Laravel 5.8

I have no idea why I keep getting this lately by just simply navigate between pages.
Call to a member function setCookie() on null
This is what I have in my AdminMiddleware
<?php
namespace App\Http\Middleware;
use App\Article;
use Closure, View, Auth ;
use Illuminate\Contracts\Auth\Guard;
class AdminMiddleware
{
/**
* The Guard implementation.
*
* #var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* #param Guard $auth
* #return void
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ( Auth::user()->type !== "Admin") {
return View::make('layouts.share.errors.404');
}
return $next($request);
}
}
I'm on Laravel 5.8.
The error occurs when you are logged in as a non Admin because you are returning a View in your AdminMiddleware instead of a Response.
Replace:
if ( Auth::user()->type !== "Admin") {
return View::make('layouts.share.errors.404');
}
With:
if ( Auth::user()->type !== "Admin") {
return response()->view('layouts.share.errors.404', [], 404);
}
To expand on #Chin Leung's answer and to properly return a 404 not found status code
if ( Auth::user()->type !== "Admin") {
return response()->view('layouts.share.errors.404', [], 404);
}

Laravel - Redirect authenticated users

In my Laravel application I have a registration system that uses the default scaffolding created via php artisan make:auth to register new users, but after logging in I wanted to take the user to another page called member-type so that they can select what type of member they'd like to be.
I utilitized protected function authenticated(Request $request, $user) which comes from AuthenticatesUsers to check that a user has successfully logged in, I then check whether a member type is set.
The method looks like this:
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
Log::info("{$user->log_reference} logged in to their account with IP: {$request->getClientIp()}");
if(!$user->investor_type_selected){
// dd('I NOT SELECTED');
return redirect()->route('user.investor-type');
} elseif(!$user->member_type_selected){
dd('M NOT SELECTED');
return redirect()->route('user.member-type');
} else{
dd('BOTH SELECTED');
return redirect()->route('user.dashboard');
}
}
The methods member_type_selected andinvestor_type_selectedcome from myUser` model and they look like this:
/**
* Check whether this user has selected an investor type
*/
public function getInvestorTypeSelectedAttribute()
{
return !empty($this->investor_type) ? true : false;
}
/**
* Check whether this user has selected an investor type
*/
public function getMemberTypeSelectedAttribute()
{
return !empty($this->member_type) ? true : false;
}
Pretty simple stuff.
The dump and die was there to test whether the statements were executing.
Anyway, the issue I have is with the Middleware RedirectIfAuthenticated which looks like this as I'm using a custom guard:
/**
* 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 = null)
{
switch ($guard) {
case 'admin':
if (Auth::guard($guard)->check()) {
return redirect()->route('admin.dashboard');
}
break;
default:
if (Auth::guard($guard)->check()) {
return redirect()->route('user.dashboard');
}
break;
}
return $next($request);
}
Now, as soon as a user is authenticated this kicks in and bypasses my redirects with authenticated. I need this Middleware generally to make sure users get back to their dashboard, but is there a way to prevent this bypassing my redirects?
no need to override authenticated function , try this in your RedirectIfAuthenticated middleware
public function handle($request, Closure $next, $guard = null)
{
switch ($guard) {
case 'admin':
if (Auth::guard($guard)->check()) {
return redirect()->route('admin.dashboard');
}
break;
default:
if (Auth::guard($guard)->check()) {
$user = Auth::guard($guard)->user();
if(!$user->investor_type_selected){
return redirect()->route('user.investor-type');
} elseif(!$user->member_type_selected){
return redirect()->route('user.member-type');
} else{
return redirect()->route('user.dashboard');
}
}
break;
}
return $next($request);
}

I want to redirect users when they after login, to profile page

I want to redirect user to profile page when they log in. But, it directs the to home ('/') page. Sometimes, it works if I open it in incognito mode. but not every time.
Following is my Login controller
class LoginController extends Controller
{
use AuthenticatesUsers;
protected function redirectTo()
{
return '/profile';
}
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct(Request $request)
{
if($email = $request->user) {
$user = User::where('email', $email)->first();
if($user && $user->auto_login_key == $request->key) {
Auth::loginUsingId($user->id);
} else {
Redirect::to('/login')->send();
}
}
$this->middleware('guest')->except('logout');
}
}
And this is my Redirected authenticated miidleware
class RedirectIfAuthenticated
{
/**
* 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 = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/profile');
}
return $next($request);
}
}
You can use return redirect('/profile'); inside your authentication function, for exmaple:
public function __construct(Request $request)
{
if($email = $request->user) {
$user = User::where('email', $email)->first();
if($user && $user->auto_login_key == $request->key) {
Auth::loginUsingId($user->id);
return redirect('/profile');
} else {
Redirect::to('/login')->send();
}
}
$this->middleware('guest')->except('logout');
}
Don't change anything, anywhere. In your LoginController, just change your $redirectTo variable to '/profile':
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/profile';
As it is working in incognito, the issue is just with cache. You can hard-reload (reload and clear cache) by pressing Ctrl + F5
AS i understand your problem, you have to first clear cache after that type of changes and make sure your browser cache is clear.
return redirect('/profile');

Multi Auth Laravel 5.4 using two middleware only

I want to create two middleware to redirect the authenticated user, if it is an admin it will be redirected to the backoffice otherwise it will be redirected to a simple dashboard for simple users.
But I want to use only the users table without adding another table for the admins.
RedirectIfAuthenticated.php
<?php
class RedirectIfAuthenticated
{
/**
* 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 = null)
{
if (Auth::guard($guard)->check()) {
if (Auth::user()->role_id == 1)
{
return redirect('/admin/home');
}
return redirect('/dashboard');
}
return $next($request);
}
}
DashboardController.php
class DashboardController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('authFront.layoutAuthenticatedUser.dashboard');
}
}
web.php
Route::get('/us-admin', function () { return redirect('/admin/home'); })->name('admin.dashboard');
// Authentication Routes...
$this->get('login', 'Auth\LoginController#showLoginForm')->name('auth.login');
$this->post('login', 'Auth\LoginController#login')->name('auth.login');
$this->post('register', 'Auth\RegisterController#register')->name('auth.register');
$this->post('logout', 'Auth\LoginController#logout')->name('auth.logout');
// Change Password Routes...
$this->get('change_password', 'Auth\ChangePasswordController#showChangePasswordForm')->name('auth.change_password');
$this->patch('change_password', 'Auth\ChangePasswordController#changePassword')->name('auth.change_password');
// Password Reset Routes...
$this->get('password/reset', 'Auth\ForgotPasswordController#showLinkRequestForm')->name('auth.password.reset');
$this->post('password/email', 'Auth\ForgotPasswordController#sendResetLinkEmail')->name('auth.password.reset');
$this->get('password/reset/{token}', 'Auth\ResetPasswordController#showResetForm')->name('password.reset');
$this->post('password/reset', 'Auth\ResetPasswordController#reset')->name('auth.password.reset');
Route::group(['middleware' => ['auth'], 'prefix' => 'admin', 'as' => 'admin.'], function () {
Route::get('/home', 'HomeController#index');
});
Route::get('/dashboard', 'DashboardController#index');
You need to establish user roles in this case, or have an optional boolean field on the users table for is_admin. Then in middleware it would simply be something like:
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 = null)
{
if (!Auth::user()->admin()) {
return redirect()->to('user-dashboard');
}
return $next($request);
}
}
So in your case I would create a separate middleware for each role post-authorization. Then you would apply AdminMiddleware to all routes prefixed with 'admin', SimpleUserMiddleware to all other routes, for example.
You can simply check roles in RedirectIfAuthenticated middleware which do already exist by default and restrict the routes by creating an admin middleware
In app/Http/Middleware/RedirectIfAuthenticated.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* 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 = null)
{
if (Auth::guard($guard)->check()) {
if (Auth::user()->role_id == 1)
{
return redirect('/admin/home');
}
return redirect('/dashboard');
}
return $next($request);
}
}
In app/Http/Middleware/AuthenticateAdmin.php
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class AuthenticateAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (!Auth::check() || Auth::user()->role_id != 1)
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
}
else
{
return redirect()->guest('login');
}
}
return $next($request);
}
}
In app/Http/Kernal.php add this line in $routeMiddleware array
'admin' => \App\Http\Middleware\AuthenticateAdmin::class,
In routes/web.php
Route::middleware('admin')->prefix('admin')->group(function() {
Route::get('/home', 'HomeController#index')->name('admin.home');
});
In app/Http/Controllers/Auth/LoginController.php add this function
protected function authenticated(Request $request, $user)
{
if ($user->role_id == 1) {
return redirect()->intended(route('admin.home'));
}
return redirect()->intended(route('dashboard'));
}
Hope this helps you

How to make online user become out in laravel 5.3

I have an admin account and user acount so
I want to make an online user become out and deny all navigation immediately from my admin account when i set $user->active to 0:
$user->active = 0;
You want to logout the user once the status changed to inactive?
If this is the case you can do
public function updateUserStatus(){
$user = Auth::user();
$user->active = false;
$user->save();
Auth::logout();
return redirect("/home");
}
I have decided to use a middleware :
step 1: in terminal
php artisan make:middleware ActiveCompt
Step 2 set the middleware :
<?php
namespace App\Http\Middleware;
use Auth;
use Closure;
class ActiveCompt
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::check()){
if ($request->user()->statut == 1) {
return redirect('logout');
}
}
return $next($request);
}
}
step 3 : defining the route Of. in karnel.php
protected $routeMiddleware = [
.
.
.
'ActiveCompt' => \App\Http\Middleware\ActiveCompt::class,
];
step 4 : calling the middleware ActiveCompt from the constructors
$this->middleware('ActiveCompt');

Categories