Laravel 5.3 and 5.4 Custom Route File - laravel

According to the Laravel Documentation, in routing section, the files located in the route directory are automatically loaded by the framework.
All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by the framework.
So, I tried to create another file in this directory called auth.php for handling my custom authentication routes. But, the routes defined in this file are not loaded.
It is possible to use this approach, or I need to register a service provider to load custom route files?

You need to map routes in your RouteServiceProvider.php, Check the example of web routes.
/**
* 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');
});
}

Related

Laravel: Multiple routes with same location and name

In my laravel(7.x) application, I am trying to bind two routes admin/ and admin/dashboard with same name. While running the php artisan route:list command, I am getting an error that Unable to prepare route [admin/dasboard] for serialization. Another route has already been assigned name [admin.dashboard].
Web.php
Route::group([ 'prefix' => 'admin' ], function() {
...
/**
* Dashboard
*/
Route::get('/', 'Backend\DashboardController#index')->name('admin.dashboard');
Route::get('/dasboard', 'Backend\DashboardController#index')->name('admin.dashboard');
});
It was working fine in the previous versions of laravel.
How to fix this..?
You are using named routes i.e. ->name(admin.dashboard) twice but named route must be unique that is why you are getting error
Route::get('/', 'Backend\DashboardController#index')->name('admin.dashboard');
Route::get('/dasboard', 'Backend\DashboardController#index')->name('admin.dashboard');
To solve this change any one of your route to something else for e.g
Route::get('/', 'Backend\DashboardController#index')->name('admin'); // changed admin.dashboard to admin
Route::get('/dasboard', 'Backend\DashboardController#index')->name('admin.dashboard');
You can't have two routes with the same names.
Route::group([ 'prefix' => 'admin' ], function() {
...
/**
* Dashboard
*/
Route::get('/', 'Backend\DashboardController#index')->name('home.dashboard');
Route::get('/dasboard', 'Backend\DashboardController#index')->name('admin.dashboard');
});
Thank you #Sehdev...
Here is the final code that I am using. Although, even with both routes mentioned in the web.php, you can only see the route in the browser, that is written at end, which in my case is /dashboard. However, both (/, /dashboard) route are working now.
Route::namespace('Backend')->prefix('admin')->group(function() {
...
/**
* Dashboard
*/
Route::get('/', 'DashboardController#index')->name('admin.dashboard');
Route::get('/dashboard', 'DashboardController#index')->name('admin.dashboard');
});
Many thanks again :)

Using "namespace" method in RouteServiceProvder in Laravel package

I am creating a laravel package and have this setup at /packages/mycompany/mypackage.
I want to use a RouteServiceProvider to register some routes and specifically pass in a namespace so I don't have to fully qualify my controllers when using this file.
I understand that to load my routes from a package I should use loadRoutesFrom in the boot method of my main ServiceProvider:
public function boot()
{
$this->loadRoutesFrom(__DIR__.'/../../routes/api.php');
}
This works fine and I can use the routes defined there however I have to fully namespace my controllers. Ideally, I want to be able to call these simply with no namespacing (and not by wrapping them in namespace) - much like how the routes work for a Laravel app (I'm using a package).
I saw that the 'namespace' method in \App\Providers\RouteServiceProvider can define a namespace to be used in a given routes file so have been using my own RouteServiceProvider with the following method:
public function map()
{
Route::domain('api'.env('APP_URL'))
->middleware('api')
->namespace($this->namespace)
->group(__DIR__.'/../../routes/api.php');
}
(As an aside - if I use the map method here - is the loadRoutesFrom call above necessary?)
My route service provider is registered via the main Service Provider:
public function register()
{
$this->app->register(\MyCompany\MyPackage\Providers\RouteServiceProvider::class);
}
However when I access my app, I get a complaint that my controller doesn't exist - which can be fixed by properly namespacing my controllers in routes/api.php which is what I want to avoid.
Route::get('/somepath', 'MyController#show');
How do I leverage namespace so I don't have to fully qualify my controllers?
loadRoutesFrom is a helper that checks to see if the routes are cached or not before registering the routes.
You can start defining a group of routes then call loadRoutesFrom in that group in your provider's boot method:
Route::group([
'domain' => 'api'. config('app.url'), // don't call `env` outside of configs
'namespace' => $this->namespace,
'middleware' => 'api',
], function () {
$this->loadRoutesFrom(__DIR__.'/../../routes/api.php');
});
Or if you prefer the method style of setting the attributes:
Route::domain('api'. config('app.url'))
->namespace($this->namespace)
->middleware('api')
->group(function () {
$this->loadRoutesFrom(__DIR__.'/../../routes/api.php');
});
This is how Laravel Cashier is doing it:
https://github.com/laravel/cashier/blob/10.0/src/CashierServiceProvider.php#L86

How to make middleware for all the routes

I have split my routes.php file into 5 different files (admin.php routes, client.php routes and so on). Now what I want is basically in each file, I got 100 routes for example). What I need is to use middleware and apply it to all the routes that exist in my app.
Solution 1) USE ROUTE GROUP and pass middleware there. If I do that, I would need to put all my routes in route::group and I have to write route:group in 5 different files.
Is there any way to write this middleware somewhere in one place and automatically globally apply it to all routes?
You can put it inside your Kernel (app/Http/Kernel.php).
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
...
\App\Http\Middleware\YourMiddleware::class,
],
];
Note that there is also another property named $middleware which is for every single route of your application.
For more information about middleware: https://laravel.com/docs/middleware#middleware-groups

Apply Auth Middleware to All Laravel Routes

What is the correct way to authenticate all routes except login and register when I apply auth middleware in all controllers? Is there a way to apply auth middleware in one place and exclude login, register routes?
You can group all your authenticated routes like following, laravel provides a default middleware for auth and guest users
Route::group(['middleware' => ['auth']], function () {
Route::get('home', 'HomeController#index');
Route::post('save-user', 'UserController#saveUser');
Route::put('edit-user', 'UserController#editUser');
});
The above route names are just made up, please follow a proper naming convention for your routes and controllers. Also read about middlewares over here and about routing over here
you can apply middlewares in the routes.php file, what you need to do is to put all your routes on a group, and add the middleware 'auth' ( except the Auth::routes() which are already configured), for example :
Route::middleware(['first', 'second'])->group(function () {
Route::get('/', function () {
// Uses first & second Middleware
});
Route::get('user/profile', function () {
// Uses first & second Middleware
});
});
more information can be found in the docs: https://laravel.com/docs/5.7/routing#route-group-middleware
You can add middleware to your whole web.php route file by adding the middleware to your routes mapping in RouteServiceProvider.
Go to app/Providers/RouteServiceProvider.php and in mapWebRoutes(), change middleware('web') to middleware(['web', 'auth']):
protected function mapWebRoutes()
{
Route::middleware(['web', 'auth'])
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
This is (not?) totally unrelated but here's an example of a clean way to handle a lot of route files instead of throwing all your routes into a single web.php file:
Create a new method mapAdminRoutes():
protected function mapAdminRoutes()
{
Route::middleware(['web', 'auth:admin'])
->namespace('App\Http\Controllers\Admin')
->name('admin.')
->group(base_path('routes/admin.php'));
}
Map it:
public function map()
{
$this->mapWebRoutes();
$this->mapAdminRoutes(); // <-- add this
...
}
Create an admin.php file in your routes folder, then create your routes for Admin:
<?php
use Illuminate\Support\Facades\Route;
// This route's name will be 'admin.dashboard'
Route::get('dashboard', 'DashboardController#dashboard')->name('dashboard');
// This route's name will be 'admin.example'
Route::get('example', 'ExampleController#example')->name('example');
...
Now you can configure everything in 1 place, like prefix, name, middleware and namespace.
Check php artisan route:list to see the results :)

Laravel 5 routes.php not created in Laravel 5.3 but welcome page works

I'm changing this question as I have first half of answer now.
I have created 2 new Laravel apps using
composer create-project laravel/laravel myApp
Both builded fine. Both of them works i.e. the welcome page shows.
But in both cases there is no routes file in App/Http
Creating a routes file doesn't help as it ignores it.
If I create apps with 5.2 it works:
composer create-project laravel/laravel myApp 5.2.*
These have the routes file in.
How do I fix my 5.3 installation?
I'm running it on a local Windows setup.
For Laravel 5.3 routes.php doesn't exist anymore. There's now 3 x route file in a folder called routes (projectroot/routes)
In Laravel 5.3, the app/Http/routes.php file has now moved to the root routes/ directory, and it's now split into two files: web.php and api.php. As you can probably guess, the routes in routes/web.php are wrapped with the web middleware group and the routes in routes/api.php are wrapped with the api middleware group.
If you want to customize this or add your own separate routes files, check out App\Providers\RouteServiceProvider this file:
public function map()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
//
}
protected function mapApiRoutes()
{
Route::group([
'middleware' => ['api', 'auth:api'],
'namespace' => $this->namespace,
'prefix' => 'api',
], function ($router) {
require base_path('routes/api.php');
});
}
protected function mapWebRoutes()
{
Route::group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require base_path('routes/web.php');
});
}
You can customize your costume routes with change in this file.
In Latest version of Laravel framework 7.5.2 routes.php is not located inside laravel > App > Http folder.
App/Http/routes.php => this file is not available (that means not located) in latest laravel Framework
instead you can find routes folder inside laravel > routes folder
In that there will be web.php file where you have to implement your new code so that code will works good
https://i.stack.imgur.com/WvPft.png
So let me go to root routes/ directory
in that you can able to find web.php in that apply below code
https://i.stack.imgur.com/DqVyx.png
Result will be :
https://i.stack.imgur.com/3WMzW.png

Resources