Learning Management Platform for Written Tutorial Series.

Laravel 6 Controllers

Laravel 6 Controllers

Laravel Controllers glue the views and models together. When a user makes a request to a laravel application, the route receives the request then calls a method in the controller. The controller then communicates with the model if necessary to retrieve some data or perform some business logic. The controller method then loads the necessary view if needed.

In this lesson, we will show you how to create controller in laravel.

Topics to be covered

We will cover the following topics in this lesson.

  • Types of Controllers
  • Creating a Controller
  • Controller Middleware

Types of Controllers

Laravel supports the following type of controllers

  • Basic Controller - this is the most common controller that is basically a class that extends the built-in Controller class. It has no methods in it when you generate it from the terminal.
  • Single Action Controller - just as the name suggests, the single action controller only has a single method. For example, you can use it to display blog details, user profile etc.
  • Resource Controller - this type of controller is used to create resources. It comes with methods that correspond to the GET, POST, PUT, and DELETE HTTP verbs. Resource controllers can easily be bound to routes using a single name
  • API Controller - this type of controller is very similar to the resource controller except that the methods for displaying forms do not exist in the API Controller.

In the next section, we will create all of the above controller methods

Creating a Controller

We can use artisan to generate boiler plate code for our controllers. It makes things much easier and faster. In this section, we will learn how to create basic, single action, resource and API controllers from the terminal

How to create a basic controller in Laravel

Open the command line. Run the following command

php artisan make:controller HomeController

HERE,

  • php artisan make:controller HomeController calls the make:controller command of artisan to create a controller called HomeController controller.

The controller is created in app/Http/Controllers directory with the name of HomeController.php

The generated boiler-plate code for the controller is as follows

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    //
}

HERE,

  • namespace App\Http\Controllers; defines the controller namespace
  • use Illuminate\Http\Request; pulls in the Request object from the framework. The Request object contains information about the request. We will later on work with it to get data.
  • class HomeController extends Controller defines a PHP class HomeController that extends the built-in class Controller.

Our basic controller has no predefined methods. We can add our own methods to it. In the previous lessons, we added logic to routes using anonymous functions. Let's now update our code to work with controller methods instead of anonymous functions.

Add the following methods to our basic controller

public function index(){
    return 'home page';
}

public function page($url){
    return "$url page";
}

HERE,

  • public function index(){...} defines a PHP function called index. Our method simply returns a message that says home page
  • public function page($url){...} defines a PHP function called page that accepts a parameter called $url. Our method returns a string that contains the value of the $url variable.

Let's now add the following routes to /routes/web.php

Route::get('/', 'HomeController@index')->name('home');
Route::get('/pages/{name}', 'HomeController@page')->name('pages');

HERE,

  • Route::get('/', 'HomeController@index')->name('home'); maps the route / to the index method in the HomeController class and names the route home.
  • Route::get('/pages/{name}', 'HomeController@page')->name('pages'); maps the route /pages/{name} to the page method in the HomeController class. Our route accepts a parameter called name that is forwaded as an argument to the page method.

Load the following URLs in your browser

http://localhost:8000/
http://localhost:8000/pages/blog

You should be able to get the following results

home page
blog page

How to create a single action controller in Laravel

Run the following command to create a single action controller

php artisan make:controller ShowBlogPostController --invokable

HERE,

  • php artisan make:controller ShowBlogPostController --invokable the --invokable tells artisan to create a single action controller.

Open the file ShowBlogPostController.php from the directory app/Http/Controllers

The default code should be as follows

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ShowBlogPostController extends Controller
{
    public function __invoke(Request $request)
    {
        //
    }
}

HERE,

  • public function __invoke(Request $request) defines a method called __invoke that will be invoked when the route calls our single action controller.

Modify the code for the __invoke method as follows

public function __invoke($url)
{
    return "$url post details from single action controller";
}

HERE,

  • public function __invoke($url) accepts a parameter $url that in normal cicumrstances can be used to retrieve results from the database then load a view. In this introductory lesson, we are simply returning a simple method.

Let's now add a corresponding route to /routes/web.php

Route::get('blog/{url}', 'ShowBlogPostController');

HERE,

  • Route::get('blog/{url}', 'ShowBlogPostController'); defines a route /blog/{url} that accepts a single parameter url and calls the ShowBlogPostController class. Notice how the method is not specified in the route definition. This is because we are using a single action controller so Laravel knows it has to call the __invoke method that we defined on our class.

How to create a resource controller in Laravel

A resource controller is used to create, read, update and delete items from the database using a web interface. In this section, we will use artisan to generate a resource controller for a resource called Brand

Run the following command

php artisan make:controller BrandController --resource

HERE,

  • php artisan make:controller BrandController --resource creates a controller that has predefined methods for perform create, read, update and delete operations on an object.

Open the new controller BrandController.php located in app/Http/Controllers

The code should be as follows

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class BrandController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

HERE,

  • Laravel generated crud methods for us. Of course the methods are empty and we will have to do the actual implementation ourselves.

Let's now add the corresponding route for our resource controller

Route::resource('brands', 'BrandController');

HERE,

  • Route::resource('brands', 'BrandController'); the resource method on the Route class maps the resource brands to the controller BrandController. Notice we havent specified HTTP verbs to be used or route names and parameters. Laravel automatically does that for us.

Run the following command in the terminal

 php artisan route:list

You should be able to see the following routes

Laravel 6 Resource Route

How to create an API controller in Laravel

APIs are very common in web applications these days. They allow system to communicate with one another.

Run the following command in the terminal

php artisan make:controller API/BrandController --api

HERE,

  • php artisan make:controller API/BrandController --api creates a controller BrandController in a diretocry API that is within app/Http/Controllers. The option --api tells artisan to generate boilerplate code for the methods that should respond to an API's create, read, update and delete methods.

Let's now update the api.php routes file located in /routes directory like so

Route::apiResource('brands', 'API\BrandController');

HERE,

  • Route::apiResource('brands', 'API\BrandController'); apiResource method maps the resource brands to BrandController API resource controller that is located in the directory API with app/Http/Controllers.

Run the following command to list all the registered routes

php artisan route:list

You should be able to see the following results

Laravel 6 API Resource

Controller Middleware

In the previous lesson, we created two simple middleware named after and before we will now apply the same middleware. Please refer to the previous lesson on how to do that.

We will add the HomeController class and add a contructor method that we will use to load the middleware

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function __construct()
    {
        $this->middleware('before');
        $this->middleware('after')->only('index');
    }

    public function index(){
        return 'home page';
    }

    public function page($url){
        return "$url page";
    }
}

HERE,

  • public function __construct(){...} defines a constructor method for our controller.
  • $this->middleware('before'); loads the before middleware that applies to all the methods defined within the controller.
  • $this->middleware('after')->only('index'); applies the after middle to the index method only. You can also use except to exclude the specifiy method from running the middleware. For example, you can apply the auth middleware to all the methods in a protected controller and exclude the login method so that it is accessible even if the user is not logged in.

Summary

Laravel uses controllers to glue models and views together. Laravel supports basic, single action, resource and API controllers. You can use artisan to automatically create controllers. The Route class provides a number of methods for linking routes to controllers i.e. resource, apiResource etc. Middleware can also be applied to controllers in laravel using the class constructor.

What next?

In the next tutorial, we will introduce you to variables and learn what role they play in python applications. If you enjoyed this lesson then show us your appreciation by creating a free accounts.


...