I want to guest users have access to home page but in built in authentication process laravel redirects to login page. how can i give guest users access to home page?
my routes.php:
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', 'HomeController#index');
Route::get('/insert', 'HomeController#insertform');
Route::get('/job/{id}', 'JobsController#show');
Route::get('/city/{city}', 'JobsController#city');
Route::post('/insert', 'HomeController#insert');
Route::get('/cityinsert', 'HomeController#cityinsert');
Route::post('/cityinsert', 'HomeController#cityinsertpost');
});
and authenticate.php
class Authenticate
{
/**
* 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)->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}
}
and this is my kernel.php
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
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,
],
'api' => [
'throttle:60,1',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}
I prefer to exclude middleware via routes. You can do it in two ways:
Single action:
Route::post('login', 'LoginController#login')->withoutMiddleware(['auth']);
Group mode:
Route::group([
'prefix' => 'forgot-password',
'excluded_middleware' => ['auth'],
], function () {
Route::post('send-email', 'ForgotPasswordController#sendEmail');
Route::post('save-new-password', 'ForgotPasswordController#saveNewPassword');
});
Tested on Laravel 7.7
Add an exception in the middleware declaration in the construct
Route::get('/', 'HomeController#index');
for the above route to be exempted from authentication you should pass the function name to the middleware like below
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth', ['except' => 'index']);
}
}
Remove the middleware from HomeController construct:
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
//$this->middleware('auth');
}
}
I can add to Sidharth answer, that you can use several methods exeption, by including them in array:
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth', ['except' => ['index', 'show']]);
}
}
Laravel 5.5 tested.
You can also separate between middleware and except. Try this one :
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except([
'submitLogout',
'showUserDetail'
]);
}
Tested on Laravel 5.4
Add except URL to VerifyCsrfToken
app/http/middleware/VerifyCsrfToken.php
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'stripe/*',
'http://example.com/foo/bar',
'http://example.com/foo/*',
];
}
Source: Laravel Documentation CSRF exclude URL
*Tested on Lavarel 7.0 as well
Recently I need that functionality in an old Laravel project.
God bless Laravel for macroable feature :)
AppServiceProvider.php
public function boot()
{
Route::macro('withoutMiddleware', function ($excludedMiddlewares) {
$this->action['middleware'] = array_filter(
$this->action['middleware'],
function ($middleware) use ($excludedMiddlewares) {
return !in_array($middleware, $excludedMiddlewares);
});
return $this;
});
}
Then you can use it like this:
Route::get('something')->withoutMiddleware(['auth']);
Related
I am running laravel version 5.4.26
my localhost project url is : middleware.dev. first time login in this url :
middleware.dev/login
,and login successfully completed. Then enter this url :
middleware.dev/admin
,then error message bellow
This page isn’t working
middleware.dev redirected you too many times. Try clearing your
cookies. ERR_TOO_MANY_REDIRECTS
Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::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\Session\Middleware\AuthenticateSession::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,
'role'=>\App\Http\Middleware\RoleMiddleware::class,
'IsAdmin'=>\App\Http\Middleware\IsAdmin::class,
];
}
IsAdmin.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class IsAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user =Auth::user();
if ($user->isAdmin()){
return redirect()->intended('/admin');
}
return $next($request);
}
}
web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
use Illuminate\Support\Facades\Auth;
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/admin/user/roles',['middleware'=>['role','auth','web'],function (){
return 'Middleware role';
}]);
Route::get('/admin', 'AdminController#index');
AdminController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AdminController extends Controller
{
//
public function __construct()
{
$this->middleware('IsAdmin');
}
public function index(){
return 'you are administretor becuse you ar sign in the page';
}
}
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function role(){
return $this->belongsTo('App\Role');
}
public function isAdmin(){
if ($this->role['name'] =='administrator'){
return true;
}
return false;
}
}
Try this in IsAdmin middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Route;
class IsAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user =Auth::user();
if ($user->isAdmin() && Route::currentRouteAction() != 'App\Http\Controllers\AdminController#index' ){
return redirect()->intended('/admin');
}
return $next($request);
}
}
This problem is most probably due to a loop in your redirection like you redirect to a route which redirects you back to the same route forming a loop.
The problem seems to be with your logic in IsAdmin middleware. The logic reads If the user is admin then redirect to /admin otherwise pass the request where it is headed which is again /admin route.
This is where the problem is. For instance, you hit middleware.dev/admin it will cross through IsAdminmiddleware and on confirming that user is admin will again redirect it to /adminroute which creates a loop.
Try this inside IsAdmin.php Class:
public function handle($request, Closure $next)
{
$user = Auth::user();
if(!$user->isAdmin()){
return redirect('/');
}
return $next($request);
}
Hi I was following this tutorial regarding Laravel and VueJs communication.
https://www.youtube.com/watch?v=5hOMkFMxY90&list=PL3ZhWMazGi9IommUd5zQmjyNeF7s1sP7Y&index=8
I have done exactly like it was said in the tutorial. It uses a CORS package https://github.com/barryvdh/laravel-cors/
I have added the service provider middlewares everything as it was told in the tutorial but it just doesnt seem to work.
I have tried it in Laravel 5.4 and Laravel 5.3 as well.
This is my RouetServiceProvider:
namespace App\Providers;
use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* #var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* #return void
*/
public function boot()
{
//
parent::boot();
}
/**
* Define the routes for the application.
*
* #return void
*/
public function map()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
//
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* #return void
*/
protected function mapWebRoutes()
{
Route::group([
'middleware' => 'web',
'namespace' => $this->namespace,
], function ($router) {
require base_path('routes/web.php');
});
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* #return void
*/
protected function mapApiRoutes()
{
Route::group([
'middleware' => ['api' , 'cors'],
'namespace' => $this->namespace,
'prefix' => 'api',
], function ($router) {
require base_path('routes/api.php');
});
}
}
This is my middleware code in kernel
protected $middleware = [
\Barryvdh\Cors\HandleCors::class,
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
I have added its service provider too.
I have seen all the solutions here on stackoverflow but none of them seems to work. I do not need theoretical answer but a practical solution
Thanks
I have a pretty straight forward middleware:
protected $auth;
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)
{
//dd($this->auth->user());
if($this->auth->user()->id && $this->auth->user()->pastDueFees()){
\Session::flash('message','You must pay past due deal fees before using the rest of the website');
return redirect()->route('profile.investment-fees');
}
return $next($request);
}
This causes the redirect loop. I am only calling the middleware via Kernel.php.
My Kernal.php:
<?php namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel {
/**
* The application's global HTTP middleware stack.
*
* #var array
*/
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'App\Http\Middleware\VerifyCsrfToken',
'App\Http\Middleware\FeesOwed'
];
/**
* The application's route middleware.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.signed' => 'App\Http\Middleware\AuthenticateSigned',
'fees' => 'App\Http\Middleware\FeesOwed',
'auth.subscribed' => 'App\Http\Middleware\AuthenticateSubscribed',
'admin' => 'App\Http\Middleware\AuthenticateAdmin',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
];
}
thanks in advance.
You need to apply that middleware to all routes but profile.investment.fees. In your kernel, add your middleware in the $routeMiddleware array as
'alias' => \App\Http\Middleware\MyMiddleware::class,
Then in your route define a group containing that middleware, and make sure profile.investment-fees is out of it
Route::get('pif', 'MyController#pif')->name('profile.investment-fees');
//Route group
Route::group(['middleware' => 'alias'], function(){
//every other routes that need the middleware
});
Alternatively, in your middleware, you could simply avoid that specific route by ignoring it with an if else
public function handle(Request $request, Closure $next) {
if ($request->is('pif')) {
return $next($request);
}
...
}
I need help with a problem that I cannot solve by myself.
I'm using Laravel 5.1 and when I try to enable the Authenticate Middleware I receive this error.
ErrorException in Manager.php line 137:
call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Auth\Guard' does not have a method 'handle'
I have the middleware as it comes by default with Laravel, also the kernel.php, both look like this
<?php
namespace Imuva\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class Authenticate {
/**
* 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 ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('auth/login');
}
}
return $next($request);
}
}
And the kernel:
protected $routeMiddleware = [
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \Imuva\Http\Middleware\RedirectIfAuthenticated::class,
'auth' => \Imuva\Http\Middleware\Authenticate::class,
];
And I use it from here:
class HomeController extends Controller {
public function __construct() {
$this->middleware('auth', ['only' => 'admin']);
}
I dont know what could be happening at all. Thanks for reading
I think you are mixing up everything you found regarding middlewares.
Why calling $this->middleware('auth', ['only' => 'admin']); on your constructor? Have a read here
Your handle method signature is : public function handle($request, Closure $next). You are passing an array as well?
How do you mange your users roles?
i have a middleware class from another laravel application in 5.0, it will be called when user login, i want to use in another application in 5.2, here is the class.
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Routing\Middleware;
use Illuminate\Contracts\Routing\ResponseFactory;
use App\AssignedRoles;
class Admin implements Middleware {
/**
* The Guard implementation.
*
* #var Guard
*/
protected $auth;
/**
* The response factory implementation.
*
* #var ResponseFactory
*/
protected $response;
/**
* Create a new filter instance.
*
* #param Guard $auth
* #param ResponseFactory $response
* #return void
*/
public function __construct(Guard $auth,
ResponseFactory $response)
{
$this->auth = $auth;
$this->response = $response;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->check())
{
$admin = 0;
$user_roles = AssignedRoles::join('roles','role_user.role_id','=','roles.id')
->where('user_id', $this->auth->user()->id)->select('roles.is_admin')->get();
foreach($user_roles as $item)
{
if($item->is_admin==1)
{
$admin=1;
}
}
if($admin==0){
return $this->response->redirectTo('/');
}
return $next($request);
}
return $this->response->redirectTo('/');
}
}
i'm already added in kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin' => \App\Http\Middleware\Admin::class,
'age' => \App\Http\Middleware\Age::class,
];
I 'm finding the cues the app in 5.0 how it call the middleware but still have no idea, here is the route:
Route::get('/', 'HomeController#index');
Route::get('home', 'HomeController#index');
Route::get('about', 'PagesController#about');
Route::get('contact', 'PagesController#contact');
Route::pattern('id', '[0-9]+');
Route::get('news/{id}', 'ArticlesController#show');
Route::get('video/{id}', 'VideoController#show');
Route::get('photo/{id}', 'PhotoController#show');
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
if (Request::is('admin/*'))
{
require __DIR__.'/admin_routes.php';
}
But how can i run it everytime in login?
Try this:
Route::group(['middleware' => 'your-middleware'], function () {
Route::post('/login', 'SiteController#login');
});
See, if that helps.
try This
Route::get('page', ['middleware' => 'auth', urController#action]);