Icon
Get In Touch
#laravel

Understanding Controllers

As your Laravel application grows, you will want to keep your code clean and organised. Instead of writing all your logic directly in routes, Laravel provides Controllers to help separate logic and make your code more manageable. Controllers act as the middle layer between your routes and views.

Creating a Controller

To create a new controller, run:

1
php artisan make:controller UserController

This command creates a file called UserController.php in the app/Http/Controllers/ directory.

Basic Controller Methods

Lets create a few basic methods in our UserController that handle common user actions like listing users, showing a single user, and adding a new user.

Open UserController.php and add the following methods:

1
<?php
2
3
namespace AppHttpControllers;
4
5
use IlluminateHttpRequest;
6
7
class UserController extends Controller
8
{
9
// Show all users
10
public function index()
11
{
12
$users = ['John Doe', 'Jane Doe', 'Mary Jane']; // Sample user list
13
return view('users.index', compact('users'));
14
}
15
16
// Show a single user
17
public function show($id)
18
{
19
$user = 'User ' . $id; // Just an example, normally you'd fetch from DB
20
return view('users.show', compact('user'));
21
}
22
23
// Add a new user (just an example)
24
public function create()
25
{
26
return view('users.create');
27
}
28
29
public function store(Request $request)
30
{
31
// Logic to save new user
32
$newUser = $request->input('name'); // Get the user input
33
return 'User ' . $newUser . ' created successfully!';
34
}
35
}

Defining Routes for Your Controller

Now that we have methods in our controller, we need to define routes that call these methods.

In routes/web.php, define routes that map to your UserController methods:

1
use AppHttpControllersUserController;
2
3
// Route for showing all users
4
Route::get('/users', [UserController::class, 'index']);
5
6
// Route for showing a single user
7
Route::get('/users/{id}', [UserController::class, 'show']);
8
9
// Route for showing the form to add a new user
10
Route::get('/users/create', [UserController::class, 'create']);
11
12
// Route for storing a new user
13
Route::post('/users', [UserController::class, 'store']);

Creating Views for Your Controller

Create the index.blade.php file in the resources/views/users/ directory:

1
<!-- resources/views/users/index.blade.php -->
2
3
<!DOCTYPE html>
4
<html lang="en">
5
<head>
6
<meta charset="UTF-8">
7
<meta name="viewport" content="width=device-width, initial-scale=1.0">
8
<title>All Users</title>
9
</head>
10
<body>
11
<h1>All Users</h1>
12
<ul>
13
@foreach($users as $user)
14
<li>{{ $user }}</li>
15
@endforeach
16
</ul>
17
</body>
18
</html>

Create the show.blade.php file:

1
<!-- resources/views/users/show.blade.php -->
2
3
<!DOCTYPE html>
4
<html lang="en">
5
<head>
6
<meta charset="UTF-8">
7
<meta name="viewport" content="width=device-width, initial-scale=1.0">
8
<title>User Profile</title>
9
</head>
10
<body>
11
<h1>User Profile</h1>
12
<p>{{ $user }}</p>
13
</body>
14
</html>

Create the create.blade.php file:

1
<!-- resources/views/users/create.blade.php -->
2
3
<!DOCTYPE html>
4
<html lang="en">
5
<head>
6
<meta charset="UTF-8">
7
<meta name="viewport" content="width=device-width, initial-scale=1.0">
8
<title>Create User</title>
9
</head>
10
<body>
11
<h1>Create a New User</h1>
12
<form action="/users" method="POST">
13
@csrf
14
<label for="name">User Name:</label>
15
<input type="text" id="name" name="name">
16
<button type="submit">Create User</button>
17
</form>
18
</body>
19
</html>

In the form, we use the POST method to send data to the /users route. The @csrf directive helps protect your app against cross-site request forgery attacks.

Handling Data from Forms

In the store() method of our controller, we handle the data submitted from the create form:

1
public function store(Request $request)
2
{
3
// Fetch the 'name' input from the form
4
$newUser = $request->input('name');
5
6
// Normally, you would save this to the database
7
// For now, we'll return a simple confirmation message
8
return 'User ' . $newUser . ' created successfully!';
9
}

When you submit the form on the create page, Laravel will send the data to the store() method, which will process the input and return a confirmation message.

Why Use Controllers?

You might wonder why we use controllers instead of writing logic directly in routes. Here are a few reasons:

Separation of Concerns: Controllers help separate your routing logic from your business logic. Routes focus on URLs and HTTP methods, while controllers handle data processing.

Reusability: You can reuse controller methods across different routes, which reduces code duplication.

Cleaner Code: Your routes file remains clean and readable since the bulk of your application logic is handled in the controllers.

Easier Testing: Controllers make it easier to test your application's business logic in isolation from the routing layer.

©2024 Codeblockz

Privacy Policy