What is Controller in Laravel?
In Laravel, a controller is a class that handles the logic for processing incoming requests and returning responses.
Controllers play a crucial role in the Model-View-Controller (MVC) architectural pattern that Laravel follows. They help to keep your application organized and separate the concerns of handling HTTP requests, processing data, and rendering views.
Creating a Controller:
To create a controller in Laravel, you can use the Artisan command-line tool. Open your terminal or command prompt and navigate to your Laravel project's root directory.
php artisan make:controller YourControllerName
This command will create a new controller file in the app/Http/Controllers directory.
Example:
Let's consider a simple example of a controller with a method that returns a view. Open the newly created controller file, which should be named something like YourControllerName.php, and define a method inside it.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class YourControllerName extends Controller
{
public function index()
{
return view('your-view-name');
}
}
In the example above:
- YourControllerName is the name you provided when creating the controller.
- The index method is a sample method that returns a view named 'your-view-name'. You would replace this with the actual logic you need.
Routing to the Controller:
Once your controller is created, you need to define a route that points to it. Open the routes/web.php file and add a route.
use App\Http\Controllers\YourControllerName;
Route::get('/your-route', [YourControllerName::class, 'index']);
Replace 'your-route' with the actual route you want, and 'index' with the method name inside your controller.