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:
1php 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<?php23namespace AppHttpControllers;45use IlluminateHttpRequest;67class UserController extends Controller8{9// Show all users10public function index()11{12$users = ['John Doe', 'Jane Doe', 'Mary Jane']; // Sample user list13return view('users.index', compact('users'));14}1516// Show a single user17public function show($id)18{19$user = 'User ' . $id; // Just an example, normally you'd fetch from DB20return view('users.show', compact('user'));21}2223// Add a new user (just an example)24public function create()25{26return view('users.create');27}2829public function store(Request $request)30{31// Logic to save new user32$newUser = $request->input('name'); // Get the user input33return '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:
1use AppHttpControllersUserController;23// Route for showing all users4Route::get('/users', [UserController::class, 'index']);56// Route for showing a single user7Route::get('/users/{id}', [UserController::class, 'show']);89// Route for showing the form to add a new user10Route::get('/users/create', [UserController::class, 'create']);1112// Route for storing a new user13Route::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 -->23<!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@endforeach16</ul>17</body>18</html>
Create the show.blade.php file:
1<!-- resources/views/users/show.blade.php -->23<!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 -->23<!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@csrf14<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:
1public function store(Request $request)2{3// Fetch the 'name' input from the form4$newUser = $request->input('name');56// Normally, you would save this to the database7// For now, we'll return a simple confirmation message8return '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