Press ESC to close

Laravel Controller

  • Jun 19, 2024
  • 2 minutes read
  • 95 Views

What is controller.?

Laravel is an MVC based PHP framework. In MVC architecture, ‘C‘ stands for ‘Controller‘.

A Controller is responsible for managing the behavior of a request. It handles requests received from the Routes.

In Laravel, a controller is located in the ‘app/Http/Controllers ’ directory.

We can create a controller using ‘make:controller ’ Artisan command.

There are two types of controllers.

  1. Basic controller
  2. Resource controller
php artisan make:controller {controller-name}

The artisan command generates a basic controller . You can see the image below.

image.png
php artisan make:controller {controller-name} -r

The artisan command generates a resource controller . ‘-r’ stands for resource  You can see the image below.

image-1.png

After creating a controller, if you create a basic controller , you will need to create a public function in the controller.

<?php 
namespace App\Http\Controllers; 
use Illuminate\Http\Request; 
class TestController extends Controller { 
    public function index() { 
        return view('view-name'); 
    } 
} 

Following the creation of the function, you will need to register or define this controller in web.php file in ‘routes ’ directory

Route::get('/', 'TestController@index')

If you are creating a resource controller , you can register or define it as follows:

Route::resources('test','TestController')

It is also possible to create functions within a resource controller and register them in web.php.

Thanks 😊 

Leave a comment

Your email address will not be published. Required fields are marked *