I decided to dig into middleware, because I need to check on every request if the user is a pre-user (just a user that hasn't changed password yet), except for the change-password route. My code for the middleware is following:
<?php
namespace App\Http\Middleware;
use Closure;
class IsPreuser
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (\Auth::user()->is_preuser)
{
if (\Route::getCurrentRoute()->getName() == 'profile.change_password')
{
echo 'hello';
}
//return redirect()->route('profile.change_password');
}
return $next($request);
}
}
My route name is profile.change_password. With the above code I am getting the error Call to a member function getName() on null I don't understand. My goals are: to redirect to the profile.change_password route except when the user already is in this route.
My 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,
\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\IsPreuser::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,
];
}
Okay, fixed it. As suggested in the comments, the problem could be the placement of my middleware. I moved it to $middlewareGroups in web and it works as expected, with the redirect.
<?php
namespace App\Http\Middleware;
use Closure;
class IsPreuser
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (\Auth::check())
{
if (\Auth::user()->is_preuser)
{
if (! $request->routeIs('profile.change_password')
&& ! $request->routeIs('profile.change_password_process')
&& ! $request->routeIs('logout'))
{
return redirect()->route('profile.change_password');
}
}
}
return $next($request);
}
}
Related
Fleet cart using middlewares in routes but i can not find any $routemiddleware in project...not even in kernel.php ...where can i find it?
Laravel Version : 5.7
Passport Version : 7.5
CMS : FleetCart
Kernel.php
namespace FleetCart\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 = [
\FleetCart\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\FleetCart\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\FleetCart\Http\Middleware\TrustProxies::class,
\FleetCart\Http\Middleware\RedirectToInstallerIfNotInstalled::class,
\FleetCart\Http\Middleware\RunUpdater::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\FleetCart\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\FleetCart\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 = [
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}
\Modules\Accounts\Routes\public.php
Route::middleware('auth')->group(function () {
Route::get('account', 'AccountDashboardController#index')->name('account.dashboard.index');
Route::get('account/profile', 'AccountProfileController#edit')->name('account.profile.edit');
Route::put('account/profile', 'AccountProfileController#update')->name('account.profile.update');
Route::get('account/orders', 'AccountOrderController#index')->name('account.orders.index');
Route::get('account/orders/{id}', 'AccountOrderController#show')->name('account.orders.show');
Route::get('account/wishlist', 'AccountWishlistController#index')->name('account.wishlist.index');
Route::delete('account/wishlist/{productId}', 'AccountWishlistController#destroy')->name('account.wishlist.destroy');
Route::get('account/reviews', 'AccountReviewController#index')->name('account.reviews.index');
});
Where that middleware('auth') came from? there is not anyother kernel files not anyother middleware representations. nothing.....!!
Looking for help!
The auth middleware is registered in the Modules/Core/Providers/CoreServiceProvider.php file.
Check the registerMiddleware() method.
To authenticate API with Fleetcart, you need to create an API specific middleware and register it under
Modules/Core/Providers/CoreServiceProvider.php
You will now have two middleware for authentication one for application auth and one for api auth
'auth' => \Modules\Core\Http\Middleware\Authenticate::class,
'api' => \Modules\Core\Http\Middleware\APIAuthenticate::class,
Under your APIAUthenticate middleware class, perform your authentication check. for below I am checking request header if it contains a Bearer token then checking the db for user with the token.
<?php
namespace Modules\Core\Http\Middleware;
use Closure;
use Log;
use Modules\User\Entities\User;
class APIAuthenticate
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return \Illuminate\Http\Response
*/
public function handle($request, Closure $next)
{
if ($request->header('Authorization')) {
$key = explode(' ',$request->header('Authorization'));
Log::info(json_encode($key));
if(isset($key[1]) && !empty($key[1])){
Log::info('key: '. $key[1]);
$user = User::where('api_token', $key[1])->first();
Log::debug('user', array($user));
if(!empty($user)){
return $next($request);
}else{
return response()->json(['error'=>'Unauthenticated']);
}
}
}else{
return response()->json(['error'=>'Unauthenticated']);
}
return response()->json(['error'=>'Unauthenticated']);
}
}
I have middleware called IsAdmin, here is the code for it:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
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->role === 10)
{
Session::flash('error', 'Трябва да сте администратор за да видите тази страница.');
return redirect('/home');
}
return $next($request);
}
}
here is registering it in the kernel:
<?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,
\App\Http\Middleware\TrustProxies::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,
'isadmin' => \App\Http\Middleware\IsAdmin::class,
];
}
and here is how I am protecting the routes in the controllers:
public function __construct()
{
$this->middleware(['auth', 'isadmin']);
}
the auth middleware works just fine.
The isadmin middleware stopped working when I changed the permission field I use in the database, on the user model. It used to be "$user->is_admin" and I've changed it to "$user->role" now even reverting back to the old way doesn't fix the problem.
Here is also the migration for the User model:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->tinyInteger('role')->default(0);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Here are also my routes or web.php file:
<?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!
|
*/
Route::get('/', function () {
return view('auth.login');
});
Auth::routes();
Route::get('/home', 'ReportController#home')->name('home');
Route::get('/dashboard', 'HomeController#dashboard')->name('dashboard');
Route::resource('/obekti', 'ObektiController');
Route::resource('/entrances', 'EntrancesController');
Route::resource('/apartments', 'ApartmentsController');
Route::resource('/people', 'PeopleController');
Route::resource('/boardmembers', 'BoardMembersController');
Route::resource('/companies', 'CompaniesController');
Route::get('/apartments/{id}/people', 'ApartmentsController#people');
Route::get('/entrances/{id}/apartments', 'EntrancesController#apartments');
Route::get('/obekti/{id}/entrances', 'ObektiController#entrances');
Route::get('/obekti/{id}/boardmembers', 'ObektiController#boardMembers');
Route::post('/search', 'HomeController#search');
If you are including your middleware inside $routeMiddleware property then you can use the middleware method to assign middleware to a route:
try this
Route::get('/dashboard', 'HomeController#dashboard')->name('dashboard')->middleware(['isadmin','auth']);
or you can use the group method
Route::group(['middleware' => ['isadmin', 'auth']], function () {
//
});
The problem was this line:
if ($user->role === 10)
it should've been this:
if ($user->role === 0)
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);
}
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 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']);