How to Create and Run Controller in Laravel 10?

Last updated on September 18, 2023 by Siraj Ul Haq

In the Laravel framework, we can create a controller by using the artisan command. To create a controller run the below command in the terminal that will create a controller file in the ‘app/Http/Controllers’ directory.

php artisan make:controller YourControllerName

Make sure the controller name ends with “Controller”, for example, if we need a student controller then it should be “StudentController”.

A controller manages how requests behave and responds to them. It processes requests sent by routes. Laravel keeps the controller files inside the ‘app/Http/Controllers’ directory. All controllers we create in the Laravel application should be placed in the ‘app/Http/Controllers’ directory. In the Laravel framework, the Controllers are implemented as PHP classes.

Let’s create a controller along with a method and route.

Create a Controller in Laravel

To create the controller in Laravel, open the terminal and run the below command that will create the controller class in the app/Http/Controllers directory.

php artisan make:controller StudentController

The controller name should follow the PascalCase, also known as UpperCamelCase which is a convention used in programming and naming conventions.

Once we run the above command, the controller file will be created.

class StudentController extends Controller
{

   public function show(){
     return view('student.profile');
   }

}

Above, we created StudentController along with a show method that simply loads the profile.blade.php file from the student folder.

Run Controller in Laravel

To run a controller, we need a route that calls the controller. we create the route in the web.php from the routes directory.

use App\Http\Controllers\StudentController;
Route::get('/student-profile',[StudentController::class,'show']);

The route() function takes two parameters. In the first parameter, we put the route name, and in the second parameter, we put the class and method name.

If you are using a local web server then run the below command in the terminal that will run the Laravel on the development server.

php artisan serve

Now you can access and run the StudenController and show() method through the below URL,

http://127.0.0.1:8000/student-profile

If your Laravel application is deployed on the server then you can simply add ‘student-profile’ slug into your domain. For example, https://yourdomain.com/student-profile

Conclusion:

This article demonstrates creating and executing controllers in the Laravel framework step by step.


Share on:

Related Posts

Tags: Laravel,