
Open the command prompt
Execute the following command to create UserController
C:\xampp\htdocs\laraveldev>php artisan make:controller UserController
After successful execution, you will receive the following output.
Controller created successfully.
You can see the created controller at app/Http/Controller/UserController.php with some basic coding already written for you and you can add your own coding based on your need.
Controller Middleware
Middleware can also be assigned to controller’s route or within your controller’s constructor. You can use the middleware method to assign middleware to the controller. The registered middleware can also be restricted to certain method of the controller.
Assigning Middleware to Route
1 2 3 4 | Route::get( 'profile' , [ 'middleware' => 'auth' , 'uses' => 'UserController@showProfile' ]); |
1 2 3 4 5 6 7 8 9 10 11 | <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class UserController extends Controller { public function __construct(){ $this ->middleware( 'auth' ); } } |
Example
Step 1 − Add the following lines to the app/Http/routes.php file and save it.
1 2 3 4 5 | <?php Route::get( '/usercontroller/path' ,[ 'middleware' => 'First' , 'uses' => 'UserController@showPath' ]); |
php artisan make:middleware FirstMiddleware
Add the following code in the handle method of the newly created FirstMiddleware at app/Http/Middleware.1 2 3 4 5 6 7 8 9 10 11 | <?php namespace App\Http\Middleware; use Closure; class FirstMiddleware { public function handle( $request , Closure $next ) { echo ' First Middleware'; return $next ( $request ); } } |
php artisan make:middleware SecondMiddleware
Step 5 − Add the following code in the handle method of the newly created SecondMiddleware at app/Http/Middleware.
1 2 3 4 5 6 7 8 9 10 11 | <?php namespace App\Http\Middleware; use Closure; class SecondMiddleware { public function handle( $request , Closure $next ){ echo ' Second Middleware'; return $next ( $request ); } } |
php artisan make:controller UserController
Step 7 − After successful execution of the URL, you will receive the following output −Controller created succesfully
Step 8 − Copy the following code to app/Http/UserController.php file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class UserController extends Controller { public function __construct(){ $this ->middleware( 'Second' ); } public function showPath(Request $request ){ $uri = $request ->path(); echo '<br>URI: ' . $uri ; $url = $request ->url(); echo '<br>' ; echo 'URL: ' . $url ; $method = $request ->method(); echo '<br>' ; echo 'Method: ' . $method ; } } |
php artisan serve
Step 10 − Visit the following URL. http://localhost:8000/usercontroller/path