Laravel — P24- Controllers Intro

Navigating Laravel: An Introduction to Controllers

For the past 23 articles, I’ve been screaming on the inside, since we haven’t been doing things the right way. Can all logic fall into your route? Sure it can. Should it? Absolutely not. This was my way easing you into Laravel. If you’ve ever read anything else on it, what’s usually the first example? “Alright guys, let’s create a to-do list.” That’s great, but it uses way too many concepts at the same time without going into enough detail about what everything else does. Enough of that, it’s time for controllers.

What are Controllers?

The best way that I can explain it is that the controller is a class that gathers the necessary information that the view needs, provides it to the view, and then returns that view.

What does this mean? Let’s say that we want to see someone’s profile. That profile information is not hard-coded; it’s instead stored in some database table. Let’s see the steps that a typical Laravel application goes through (some stuff omitted for clarity):

  • The user clicks on their portfolio link.
  • GET request is sent to the routes/web.php file. If a route exists that matches what we wanted, Laravel enters that route.
  • Within the route, a call to a specific Controller method is made. The results will be returned to the user.
  • Laravel enters the specific controller’s method.
  • Inside of the method, the Controller contacts the Model. The Model knows how to communicate with the database table.
  • The Model grabs the profile record and returns it to the Controller’s method.
  • The Controller method now has all of the information that’s necessary. It just needs to send it along.
  • The Controller then sends the information to a specific view (i.e. profile/index.
  • The view injects the code necessary and returns the HTML back to the Controller’s method.
  • The Controller’s method returns the view to the routes/web.php file’s route.
  • The route returns the HTML page back to the user.

Why not just do all of this in the route file?

Because we want to group related logic into a specific class. If we had a product in the database, we’ll probably have a ProductController. The ProductController will have functionality to:

  • show all products
  • show a single product
  • show a form to create a new product
  • process the creation of a new product
  • show a form to update a product
  • process the update of a product
  • delete a product

A product will have a brand. That brand will probably live in its own table. It needs to have the same functionality again: view all brands, show a single brand, etc.

Imagine how massive the route file would get if you had all of the logic inside of your routes/web.php file. It would be pretty difficult to read. This is where Controllers begin to shine. Your route file begins to look much simpler too.

Creating Your First Controller

Controllers are exciting, we get it. How do we create a controller now? With artisan! If you need a refresher on artisan, make sure to check out my intro on it.

https://medium.com/geekculture/laravel-p21-artisan-intro-and-route-list-d30b130b8d7

If you’ve been following along, we’re going to go into our Docker container and type in the following command:

php artisan make:controller TestController

You type in the php artisan make:controller command followed by the Controller name. By convention, it’s the name with the word Controller appended, i.e. TestController.

It says that the controller has been successfully created. Where is it? All of your controllers will live inside of the app/Http/Controllers directory.

Open it up and you’ll see a skeleton. It has no methods currently. It’s ready for you to do something with it.
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
//
}
Let’s create a couple of methods. I’ll call one, index and the other one show. The index method will return an array with a couple of entries and the show method will return an array with one entry.
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
public function index()
{
return [
            [
"make" => "Chevrolet",
"model" => "Corvette",
            ],
            [
"make" => "Porsche",
"model" => "911 GT3",
            ],
        ];
    }

public function show()
{
return [
"make" => "Porsche",
"model" => "911 GT3",
        ];
    }
}
Now what? We have to create a route for each of these in order to access them. The routes start off the same, but calling the controller methods is different than the closures that we’re used to passing. The route syntax for controllers looks like this:
<?php
Route::get('/test-controller/index', [\App\Http\Controllers\TestController::class, 'index']);
Route::get('/test-controller/show', [\App\Http\Controllers\TestController::class, 'show']);
You can import the controller so that you don’t have to show the full controller path in your route. To import the controller, we’ll need to use the use keyword.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TestController;

Route::get('/test-controller/index', [TestController::class, 'index']);
Route::get('/test-controller/show', [TestController::class, 'show']);

When you visit your routes now, you can see the response provided, which is just an array of data.

Look how much cleaner our route file looks already. Imagine if we didn’t have controllers and needed to do this:

<?php
Route::get('/test-controller/index', function() {
return [
        [
"make" => "Chevrolet",
"model" => "Corvette",
        ],
        [
"make" => "Porsche",
"model" => "911 GT3",
        ],
    ];
});

Route::get('/test-controller/show', function() {
return [
"make" => "Porsche",
"model" => "911 GT3",
    ];
});
And now imagine if we had hundreds of other routes. These are simple. What if each route had 20+ lines of code. It would be a mess. I’m thankful for Controllers. In the next article, we’ll cover passing URL arguments to controller methods.

Laravel Series

Continue your Laravel Learning.

Laravel — P23: Route Groups

Efficiency Through Organization: Laravel’s Route Groups Explained

Laravel – P23: Route Groups

Streamline your Laravel app with route groups for better structure & maintenance. Learn how to organize routes effectively.

Laravel — P24- Controllers Intro

Navigating Laravel: An Introduction to Controllers

Laravel – P24: Controllers Intro

Begin your journey with Laravel controllers to manage app logic & data flow. Discover tips for effective MVC architecture integration.

Laravel — P25: Passing URL Arguments to Controllers

Dynamic Data Handling: URL Arguments in Laravel Controllers

Laravel – P25: URL Arguments To Controllers

Learn to pass URL arguments to Laravel controllers for dynamic content delivery. Enhance user interaction with tailored responses.

Leave a Reply