In this tutorial, we aim to guide you through the process of creating controllers in Laravel. Controllers in Laravel are the traffic cops of your application that direct HTTP requests to appropriate views with data from your models.
By the end of this tutorial, you'll be able to:
Prerequisites:
- Basic understanding of PHP.
- Familiarity with Laravel framework would be beneficial.
In Laravel, a Controller is a class that is responsible for defining the application behavior in response to HTTP requests. It contains methods that are the endpoints of your routes.
To create a controller, Laravel provides an artisan command:
php artisan make:controller ControllerName
You should replace ControllerName
with the name of your controller. The new controller will be placed in the app/Http/Controllers
directory.
Basic controllers are simple classes that are placed in the app/Http/Controllers
directory. Here is an example of a basic controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function showProfile()
{
// logic here
}
}
Let's create a basic controller and route for displaying a user's profile.
php artisan make:controller UserController
UserController
, add a showProfile
method:public function showProfile()
{
return view('user.profile');
}
routes/web.php
and add:Route::get('user/profile', 'UserController@showProfile');
The UserController@showProfile
tells Laravel to use the showProfile
method of UserController
when a GET request is made to the /user/profile
URL.
In this tutorial, we've covered the basics of controllers in Laravel, including how to create them and how they interact with routes.
For further learning, you can explore resource controllers which are a special type of controller designed to handle CRUD operations with minimal effort.
Additional Resources:
Create a controller named ProductController
and add a method to display product details.
Create a route to map to the product details method in ProductController
.
Create a controller named BlogController
and add methods to create, read, update, and delete blog posts. Then, create routes for each of these methods.
Solutions:
ProductController
:php artisan make:controller ProductController
Add method to ProductController
:
public function showDetails()
{
return view('product.details');
}
Route::get('product/details', 'ProductController@showDetails');
BlogController
:php artisan make:controller BlogController
Add methods to BlogController
:
public function createPost()
{
// create post logic
}
public function readPost()
{
// read post logic
}
public function updatePost()
{
// update post logic
}
public function deletePost()
{
// delete post logic
}
Routes for BlogController
methods:
Route::get('blog/create', 'BlogController@createPost');
Route::get('blog/read', 'BlogController@readPost');
Route::get('blog/update', 'BlogController@updatePost');
Route::get('blog/delete', 'BlogController@deletePost');