LARAVEL: How to use middleware on named routes - laravel

I've been working on an app that initially didn't use middleware. Later on, I decided to add middleware and had to change my routes from something like:
Route::get('admin/poems', array('as' => 'poems', 'uses' => 'PoemsController#poem'));
to
Route::get('admin/poem', ['middleware' => 'auth', 'uses' => 'PoemsController#poem']);
Now the disadvantage is that I had been redirecting to this route (poems) several times and adding middleware as indicated will require me to go through all my code and change the name of the route in the redirect.
How do i solve this problem?
Thanks for any help.

You don't need to lose the name of your route, the array will still accept it along with your middleware.
Just add it in to look like so:
Route::get('admin/poem', ['middleware' => 'auth', 'as' => 'poems', 'uses' => 'PoemsController#poem']);
This way you don't need to go through and rename your routes anywhere and can still protect it with auth middleware.

try put middleware to a group route
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
// Uses Auth Middleware
});
Route::get('user/profile', function () {
// Uses Auth Middleware
});
});

Related

What does 'as' method do in Laravel

In the example from the tutorial, it shows up.
Route::group([
'prefix' => 'admin',
'as' => 'admin.'
], function () {}
Can someone tells me what 'as' does? Also, is the dot next to the 'admin' neccessary?
Thank you.
Let's say, for example, that you have this route:
Route::get('admin', [
'as' => 'admin', 'uses' => 'AdminController#index'
]);
By using as you assign custom name to your route. So now, Laravel will allow you to reference said route by using:
$route = route('admin');
So you don't have to build the URL manually over and over again in your code. You don't really need . notation if you only want to call your route admin. If you want a more detailed name of your route, lets say for ex. admin product route, then you use the . notation, like this:
Route::get('admin/product', [
'as' => 'admin.product', 'uses' => 'AdminController#showProduct'
]);
So now, you will be able to call this route by the assigned name:
$route = route('admin.product');
Update:
The previous answer I provided is valid for a single routes. For the route groups, the procedure is very similar. In the route groups you need the . notation when you add a custom name, since you will be referencing another route after that . notation. This will allow you to set a common route name prefix for all routes within the group. So by your example, lets say you have a dashboard route inside your admin route group:
Route::group(['as' => 'admin.'], function () {
Route::get('dashboard', ['as' => 'dashboard', function () {
//Some logic
}]);
});
Now, you will be able to call the dashboard route like this:
$route = route(admin.dashboard);
You can read more about this in Laravel official documentation.
you may specify an as keyword in the route group attribute array, allowing you to set a common route name prefix for all routes within the group.
For Example
Route::group(['as' => 'admin::'], function () {
// Route named "admin::"
});
UseRoute Name like {{route(admin::)}} or route('admin::')
you can use an 'as' as a named route. if you do not prefix your route name in group route than you may add custom route name like this.
Route::group(['prefix' => 'admin', 'middleware' => ['auth', 'roles'], 'roles' => ['2']], function () {
Route::post('/changeProfile', ['uses' => 'UserController#changeProfile',
'as' => 'changeProfile']);
});

How can I make index form resource route out of the middleware?

Now this route's without ( except ) it just find working but when I want to reach any route like index or store I must to login then get the data form them . So I want to make index route out of this middleware ( it's ok reach to index without login ) hope to got it :)
route's :
Route::group(['middleware' => 'auth:api'], function() {
Route::resource('cards', 'cardsController', ['except' => 'index']);
Route::resource('services', 'servicesController', ['except' => 'index']);
Route::get('getUserinfo', 'LoginController#getUser');
});
and this my route list for cards :
and this when I get all cards form postman :
You have ['except' => 'index'] in the route group. Try to take it out and check if it is working.
Edited:
if you want index showing without login, try writting another route outside of the route group
so something like this
Route::get('cards', 'cardsController#index');
Route::get('services', 'servicesController#index');
Route::group(['middleware' => 'auth:api'], function() {
Route::resource('cards', 'cardsController', ['except' => 'index']);
Route::resource('services', 'servicesController', ['except' => 'index']);
Route::get('getUserinfo', 'LoginController#getUser');
});
First you should name your Controllers properly, instead of
cardsController
name it to
CardsController
Your error occurs because you are excepting the index action in your Controller.
Instead of this:
Route::resource('cards', 'cardsController', ['except' => 'index']);
Route::resource('services', 'servicesController', ['except' => 'index']);
Do this:
Route::resource('cards', 'cardsController');
Route::resource('services', 'servicesController');
Check out the docs
Dont forget to name your Controller properly.
As you should define your route outside the middleware.... As u want to use it without login....
Route::get('cards', 'cardsController#index');
Route::get('services', 'servicesController#index');
In middleware u have to define the route as below
Route::resource('cards', 'cardsController')->except('index');
Route::resource('services', 'servicesController')->except('index');

How to check domain in laravel for some routes?

I need check domain for some routes. Then after check, I need redirect domain https://two.com to https://one.com with middleware in laravel.
For example:
Routes:
Route::get('/', ['as' => 'index', 'uses' => 'IndexController#index']);
Route::get('termsAndCondition', ['as' => 'termsAndCondition', 'uses' => 'IndexController#termsAndCondition']);
Route::get('aboutUs', ['as' => 'aboutUs', 'uses' => 'IndexController#aboutUs']);
Route::get('privacy', ['as' => 'privacy', 'uses' => 'IndexController#privacy']);
I need check aboutUs and privacy for domain name.
If domain name is https://two.com/aboutUs or https://two.com/privacy redirect to https://one.com/aboutUs or https://one.com/privacy.
I need check with middleware.
Thanks.
You can do something like this in a middleware:
if (request()->getHttpHost() === 'two.com' && in_array(request()->path(), ['aboutUs', 'privacy'])) {
return redirect('https://one.com/' . request()->path());
}
you can check url segments using segment() helper something like:
if(Request::segment(1)==='aboutus')
{
return redirect(route('your other route');
}
if(Request::segment(1)==='privacy')
{
return redirect(route('your other route');
}
You can add that check in your middleware, segment() expects an integer param like in case above 1 will check first wildcard after domain name.

Laravel grouping routes what is best prefix or middleware

When I start thinking grouping my routes and check the documentation. I lost there. There are too many things like prefix, middleware etc.
What is the best way to group routes?
Route::group(['middleware' => 'admin'], function () {});
Route::group(['prefix' => 'admin'], function () {});
Route::group(['namespace' => 'admin'], function () {})
Which approach is best? And why? When to use what approach?
Wait. Prefix and middleware are two different things
prefix is a way to Prefix your routes and avoid unnecessary typing e.g:
Route::get('post/all','Controller#post');
Route::get('post/user','Controller#post');
This can be grouped using prefix post
Route::group(['prefix' => 'post'], function(){
Route::get('all','Controller#post');
Route::get('user','Controller#post');
})
In the other hand, Middleware :
Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.
For example using last example now i want the users to be authenticated in my post routes. I can apply a middleware to this group like this:
Route::group(['prefix' => 'post', 'middleware' => ['auth']], function(){
Route::get('all','Controller#post');
Route::get('user','Controller#post');
})
You should check the docs to get more informed.
https://laravel.com/docs/5.5/middleware
https://laravel.com/docs/5.5/routing#route-groups
Both are different But to use both at the same time Best technique for grouping route middleware and prefix your route avoid unnecessary typing
Route::group(['prefix' => 'admin','middleware' => ['auth:admin']], function() {
Route::get('dashboard','AdminController#dashboard');
});
It may not be related to the current question, but if anyone is wondering how to use grouping prefix and middleware as well as controller in a scenario where you need auth check and then need a prefix to avoid repeat typing for the specific controller group, you may try the following way.
Route::middleware(['auth', 'verified'])
->controller(\App\Http\Controllers\AdminController::class)
->prefix('dashboard')->group(function() {
Route::get('/', 'adminIndex')->name('admin.index');
});
Or,
Route::group(['middleware' => ['auth', 'verified'], 'prefix' => 'dashboard'], function () {
Route::controller(\App\Http\Controllers\AdminController::class)->group(function (){
Route::get('/', 'adminIndex')->name('admin.index');
});
});

Laravel Routes Artisan

When I run artisan routes in laravel 4
auth/login/{v1}/{v2}/{v3}/{v4}/{v5}
Is this normal or is there something wrong. My routes work just wondering if there might be a bug or something. Below are my routes for auth. I'm using restful routes for auth.
Route::controller('auth','AuthController');
Route::get('AuthController/login', array('as' => 'login', 'uses' => 'AuthController#login'));
Route::get('auth/logout', array('as' => 'logout', 'uses' => 'auth#logout'));
Route::post('auth/login', array('uses' => 'auth#login'));
This is expected. When you register controllers with Route::controller() the controller inspector adds the URI wildcards. Consider the following example:
Route::controller('user', 'UserController');
You might then have a method like this on your UserController:
public function getProfile($username)
{
$user = User::where('username', $username)->first();
return View::make('profile')->with('user', $user);
}
You could then hit that method by going to localhost/yourapp/user/profile/jason
In a nut shell it allows you to pass extra parameters to a method. To me this is a very old school way of doing it, as it looks nicer like localhost/yourapp/user/jason/profile and in this case you'd need to use a route to map to the controller method.
I suggest you 2 improvements:
1 - keep a standard with URIs
You don't need Route::controller in this case. In order to mantain all routes with the same structure I would do:
Route::group( array('prefix'=>'auth,function(){ //make all auth routes starting by auth
Route::get('getLogin', array('as' => 'getLogin', 'uses' => 'AuthController#getLogin'));
Route::get('getLogin', array('as' => 'logout', 'uses' => 'AuthController#logout'));
Route::post('postLogin', array('as' => 'postLogin', 'uses' => 'AuthController#postLogin'));
});
It is not necessary to use group but if you app grows could be better. Without group code will be:
Route::get('auth/getLogin', array('as' => 'getLogin', 'uses' => 'AuthController#getLogin'));
Route::get('auth/getLogin', array('as' => 'logout', 'uses' => 'AuthController#logout'));
Route::post('auth/postLogin', array('as' => 'postLogin', 'uses' => 'AuthController#postLogin'));
2 - Protect your post routes
For every post and put request we've to prevent CSRF attacks like this:
Route::post('postLogin',array('before' => 'csrf','uses'=>AuthController#postLogin) );

Resources