Laravel separate Controllers for Admin/Back-end and Frontend

In the previous article, we have learned about how to separate views for admin and backend. In this one, we are going to create flexibility in Controllers folders so that we can have separate folders, i.e. AdminControllers, for admin and, i.e. FrontControllers, for the front.

This arrangement helps developers to have their structure well-organized when their application will grow at a large scale.

Let’s start doing it,

1. Laravel Distinct/Separate Controllers for Admin or Backend and Frontend

Step 1: Read the previous article to setup Laravel’s application scope

Step 2: Open app/Providers/RouteServiceProvider.php file

  1. Modify protected $namespace path to ‘App\Http\Controllers\FrontControllers’
  2. add codes in the function “mapWebRoutes”
Add FrontControllers folder to the default namespaceModify mapWebRoutes functionprotected function mapWebRoutes() { $appScope = config('app.app_scope'); if ($appScope == 'admin') { $this->namespace = 'App\Http\Controllers\AdminControllers'; } Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); }

Step 3: Create two folders, AdminControllers and FrontControllers, in app\Http\Controllers folder

Step 4: Testing

Now go to Routes/web.php file and add following routes, one for admin and one for the front.

Route::get('test', 'PageController@initContent'); // This will resolve FrontControllers/PageController.php file Route::group(['prefix' => 'admin'], function () { Route::get('dashboard', 'DashboardController@initContent'); //This will resoluve AdminControllers\DashboardController file });

Step 5: Testing: Next generate Controllers files through Laravel artisan command

php artisan make:controller FrontControllers/PageController php artisan make:controller AdminControllers/DashboardController

Now you can go to those respective controller files and add your method there and start testing them in the frontend and admin.

As I said before, this will keep your application well-organized once the codebase is substantially increased.

Source code stored on Github repository here: https://github.com/jigeshraval/laravel-separate-controllers-for-admin-back-end-and-frontend

If you have any problem or question, then, please write in the comment section below

Newsletter

Make sure to subscribe to my newsletter and be the first to know about my new post.

Subscribe on Youtube
FOR UPDATES

I post tutorials about various technologies on the youtube channel

Subscribe Now
Newsletter

Make sure to subscribe to my newsletter and be the first to know about my new post.

© 2019