Laravel 8 Controller Tutorial with Example

In this tutorial, we discuss about Laravel Controller, how to make controller, create function in laravel controller, call controller method from routing and pass parameters with URL.

What is Laravel Controller

A controller is the central unit of laravel, which handle all request sending by route files. A controller can manage group-related route requests into a single class.

For example LoginController is controller class, which handle request to showing login html form, register users, forgot password.

By default laravel controller file stored in the app/Http/Controllers directory.

How to Make Controller Laravel 8

We are showing an example of Laravel 8 version controller.

To create an controller type below command in your laravel root directory using command prompt.

In the above command ‘LoginController’ is the name of the controller file that you want to create.

Create a function in Laravel 8 Controller

After this command, you will that LoginController.php file is created under app/Http/controllers folder.

Now we are creating a show() function in this controller which will display some text.

The basic structure of a controller looks like below:

Call Controller Method from Routing

Now to call show() function, we need to create a laravel routing method for this controller method.

To create new route, go to in routes/web.php file.

In laravel 8 version, first you have to import this ‘LoginController’ inside this web.php route file. Like this

use App\Http\Contollers\LoginController

Check below route example to call this method.

Here “login” is the url parameter, which you execute to call this method like

http://localhost:8080/login

And ‘show’ is the LoginController method name which we defined in controller class.

Pass Parameter using Controller

To pass the data from url to controller method like any Name or Id

http://localhost/login?id=1234

First add the parameter in web.php get route like this

You can multiple parameters here.

Now change in show() function inside ‘LoginController’ file. Here we need to get that ‘id’ parameter value.

This will show id value in the show method, whatever you passed in the web URL.

Recommended Posts For You

About Harish

I am professional web developer and blogger. Use this blog to share own api and other web development experience with you. I do accept paid work. Write to me at - [email protected]

View all posts by Harish