Per laravel doc, I can add the auth middleware as follows:
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
// Uses Auth Middleware
});
Route::get('user/profile', function () {
// Uses Auth Middleware
});
});
I've also seen middleware added as follows:
Route::group(['middleware' => ['web']], function() {
// Uses all Middleware $middlewareGroups['web'] located in /app/Http/kernel.php?
Route::resource('blog','BlogController'); //Make a CRUD controller
});
How can I do both?
PS. Any comments providing insight on what the bottom four lines of code are doing would be appreciated
To assign middleware to a route you can use either single middleware (first code snippet) or middleware groups (second code snippet). With middleware groups you are assigning multiple middleware to a route at once. You can find more details about middleware groups in the docs.
To use both (single middleware & middleware group) you can try this:
Route::group(['middleware' => ['auth', 'web']], function() {
// uses 'auth' middleware plus all middleware from $middlewareGroups['web']
Route::resource('blog','BlogController'); //Make a CRUD controller
});
You may also assign multiple middleware to the route:
Route::get('/', function () {
//
})->middleware('first', 'second');
Reference
You could also do the following using the middleware static method of the Route facade:
Route::middleware(['middleware1', 'middlware2'])
->group(function () {
// Your defined routes go here
});
The middleware method accepts a single string for one middleware, or an array of strings
for a group of middleware.
Route::middleware(['auth:api'])->middleware(['second:middleware'])
->prefix('yourPrefix')->group(function () {
//Add your routes here
});
Related
i have a project that uses API and Web routes
web.php:
Route::middleware(['auth:sanctum',config('jetstream.auth_session'),'verified'])->group(function () {
Route::get('/admindashboard', function () { return view('dashboard');})->name('dashboard');
});
the above is working fine and i can call auth()->user() inside the blade
but here in
api.php:
Route::prefix('orders')->as('orders.')->controller(OrderController::class)->group(function(){
Route::get('index', 'index')->name('index');
});
there is no middleware and i can't use auth()->user() inside its blade
how can i wrap the above routes (in api.php) with middleware so i can use auth in balde?
Actually, it's the same middleware that you can use in apis as well.
Route::middleware('auth:sanctum')->group(function () {
// Authenticated Routes in api.php
Route::get('/user', function ()
{
return auth()->user();
});
});
I am wondering if there is any adifference between asiigning middleware in a route like this :
Route::patch('/edit/{column}/{id}',['middleware' => 'auth', 'uses' => 'ResourceController#editCompany']);
and launching it in controller's constructor
public function __construct()
{
$this->middleware('auth');
}
Is it the same? Does it do anything else then checking if I am logged in?
It is completely the same. The problem is when you add that in the constructor you need to remember to add it in every new controller that you want to be auth protected.
While in the routes file, you can group multiple endpoints and apply the middleware in all of them:
Route::group(['middleware' => 'auth'], function() {
// all routes here that need to be auth protected.
});
If I will create some application on Laravel (for example it will be project.com) and in this same application I will develop admin area (with ACL, users management, etc.). Can I use it like project.com for front-side but backoffice.project.com for admin area in same application?
Thanks.
You can maintain both applications in the same Laravel project and use grouped routes and filter your routes by domain.
Route::group(['domain' => 'backoffice.project.com'], function () {
// your BACKEND routes...
});
Route::group(['domain' => 'www.project.com'], function () {
// your FRONTEND routes...
});
You can complement the route comportment with middleware too.
// in this case all backend routes will be passed to auth middleware.
Route::group(['domain' => 'backoffice.project.com', 'middleware' => 'auth'], function () {
// your BACKEND routes...
});
Important:
Observe that the Laravel documentation talk about Sub-Domains Routing. In this case, the approach of the documentation is the use of dynamic subdomains, as can be seen in the following example.
Route::domain('{account}.myapp.com')->group(function () {
Route::get('user/{id}', function ($account, $id) {
//
});
});
In this case, {account} is a route parameter that can be used inside of the route group.
You can see (and read) more about Laravel routes here: https://laravel.com/docs/5.5/routing
Yes, you can group routes by domain.
Since Laravel 5.3 you can group them like this:
Route::domain('project.com')->group(function () {
// Your frontend routes
});
Route::domain('backoffice.project.com')->group(function () {
// Your backend routes
});
Before Laravel 5.3 you can group them like this:
Route::group(['domain' => 'project.com'], function () {
// You frontend routes
});
Route::group(['domain' => 'backoffice.project.com'], function () {
// You backend routes
});
I've simple middleware which checks if there is a key in user session.
<?php
namespace App\Http\Middleware;
use Closure;
class CustomAuth
{
public function handle($request, Closure $next)
{
if($request->session()->has('uid')){
return $next($request);
}
else{
return view('unauth');
}
}
}
The problem is that I always get "Session store not set on request." error. Here is my route:
Route::get('home', function () {
return view('home');
})->middleware('web', 'CustomAuth');
I've added the middleware in app\Http\Kernel.php in the variable $middleware
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\CustomAuth::class
];
I also tried changing my route to this:
Route::group(['middleware' => ['web']], function () {
Route::get('home', function () {
return view('home');
})->middleware('CustomAuth');
});
But this didn't work. Any idea how I can make sure that the session had started, or start it before the middleware is called? I'm using Laravel 5.3
The L5 middleware consists of 3 "types".
The configuration is found in the Kernel.php file for HTTP requests (typically App\Http\Kernel. There's global middleware which will run for all requests and is declared in $middleware, there's the route group middleware which will run for all requests for a given route group and is declared in $middlewareGroups, by default all routes declared in web.php are considered to be web routes so all the web middleware apply.
The 3rd type is route middleware. These are declared in the $routeMiddleware array in the form "middlewareName" => Middleware::class and can be used in any route e.g.
Route::get("/route", function () { /* route body */ })->middleware("middlewareName");
These run in order global > group > route middleware and the SessionStart middleware runs as part of the group middleware. Any other middleware that needs access to the session will need to be placed after the SessionStart middleware.
Clarification
It occurs to be when re-reading this that this implies that you need to declare the middleware in the $middeware variable to use them. This is not the case, the following syntax is also allowed:
Route::get("/route", function () {
/* route body */
})->middleware(Middleware::class);
However this syntax will not allow you to provide parameters to the middleware when you use them as you would for example with the authentication middleware when you do auth:api (where api would be a parameter passed to the middleware).
I'm fairly new to Laravel, so this question may obvious to some.
In the case of running checks per HTTP request, for example User Authentication. Is there a better, more efficient or simple correct way to run these checks. From my initial research it would seem that this could be accomplished using either MiddleWare, eg.
public function __construct()
{
$this->middleware('auth');
}
It also seems like it would be possible using routing groups, eg.
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
// Uses Auth Middleware
});
Route::get('user/profile', function () {
// Uses Auth Middleware
});
});
Is there any benefits of doing this either of these two ways? Apart from the obvious benefit of not having to put $this->middleware('auth'); in every controller auth would need to be checked.
Thanks
Edit..
After taking on your advice I attempted to utilities the route grouping to control my Auth MiddleWare. But this has seemed to have broken my site.
Route::group(['middleware' => 'auth'], function () {
Route::auth();
Route::get('/home', 'HomeController#index');
Route::get ( '/redirect/{provider}', 'SocialAuthController#redirect' );
Route::get ( '/callback/{provider}', 'SocialAuthController#callback' );
});
Am I missing something obvious?
You are almost there, just remove the Route::auth():
Route::group(['middleware' => 'auth'], function () {
Route::get('/home', 'HomeController#index');
//add more Routes here
});
The suggested options did not work for me but when I checked the laravel documentation, I found this:
Route::middleware(['web'])->group(function () {
//Your routes here
});
It works for me. Laravel 8.*
There is no real difference, personally i use groups for the standard middleware and put exceptions in the construct
Using Route group is easy for maintenance/modification , other wise you will have to remember each controller where you are using certain middle ware, of course this not a concern in a small medium sized application, but this will be hard in a large application where is lots of controller and references to middle ware.