How to create a controller in Laravel

Create a controller in Laravel with a step-by-step example: learn how to set up routes, controllers, and views.

Creating a Controller in Laravel

Controllers are a fundamental part of Laravel and are used to handle requests and return responses. They are often the key component of a Laravel application, and they define the logic needed to power the application. A controller is simply a PHP class which extends the base controller class provided by Laravel. This class is used to contain all of the logic for a given request. In this tutorial, we will look at how to create a controller in Laravel.

Step 1: Create the Controller

The first step is to create the controller file. This can be done using the Artisan command line tool. To create a controller, run the following command in the terminal:

php artisan make:controller MyController

This will create a controller file named MyController.php in the app/Http/Controllers directory. The contents of this file should look like this:

<?php 

namespace AppHttpControllers;

use IlluminateHttpRequest;

class MyController extends Controller
{
    //
}

Step 2: Define Your Routes

The next step is to define the routes that will be handled by our controller. This is done in the routes/web.php file. We can add a route like this:

Route::get('my-route', 'MyController@myAction');

This route will use the MyController class to handle requests to the my-route URL. The @myAction part of the route definition tells Laravel to use the myAction() method in the controller to handle the request.

Step 3: Add the Action Method

Now that we have our route defined, we can add the action method to our controller. This method will contain the logic for our route. We can add the method to the controller like this:

public function myAction()
{
   // logic goes here
}

This method will be called when a request is made to the my-route URL. We can now add our logic to the method to handle the request.

Step 4: Return a Response

The final step is to return a response from the action method. We can do this by using the response() helper method. We can use this method to return a string, an array, JSON, a view, or a redirect. For example, we can return a JSON response like this:

return response()->json([
   'message' => 'Hello World'
]);

This will return a JSON response with a message property containing the string "Hello World". We can also return a view like this:

return view('my-view');

This will return the my-view.blade.php view from the resources/views directory.

Now that we have our controller and action method defined, we can make requests to the my-route URL and our controller will handle the request and return the appropriate response.

Answers (0)