Laravel 8 Tutorial - Controllers

In this video, we will learn about controllers in Laravel. A controller acts as a directing traffic between views and models, and is the central unit where we can write logic, call database data, call models, and pass views.

Let's see how to create a controller. Switch to the command prompt and type the command to create a controller:


php artisan make:controller HomeController

Here, "HomeController" is the controller name, which should start with a capital letter. Press enter, and the HomeController will be created successfully.

Now, switch to the project and go to the app/Http/Controllers directory. You will see the HomeController file. Open it, and you will see some default code inside.

Let's create a function inside this controller. We can create a function with public, private, or protected access specifiers. By default, it is public. Type the following code:


public function index()
{
return "Hi, From HomeController";
}

Now, let's define a route for this controller. Go to the web.php file and create a route:


Route::get('/home', [HomeController::class, 'index'])->name('home.index');

Make sure to import the HomeController at the top:


use App\Http\Controllers\HomeController;

Now, let's check. Switch to the browser and go to the URL http://localhost:8000/home. You will see the output "This is HomeController".

Next, let's see how to pass parameters into the controller. We need to modify the route and the controller method. Go to the web.php file and modify the route to pass a parameter:

Now, open the HomeController and modify the method to accept the parameter:

Type echo "Hi ".$name; to print the parameter. Now, let's check. Switch to the browser and add any name to the URL. Press enter, and you will see the output.

If you want to make the parameter optional, add a ? sign to the parameter and set $name=null in the HomeController. Now, the parameter has become optional. Let's check this. Refresh the page, and it will work with or without the parameter.

That's all about Laravel controllers!