8 - 1 - Laravel (Updated)
8 - 1 - Laravel (Updated)
// Fetch a user
Route::get('/user/{id}', [UserController::class, 'show']);
// Create a user
Route::post('/user', [UserController::class, 'store']);
// Update a user
Route::put('/user/{id}', [UserController::class, 'update']);
// Delete a user
Route::delete('/user/{id}', [UserController::class, 'delete']);
Redirect Routes
Redirect routes are used in Laravel to send users from one URL to another. Laravel
provides a simple way to define redirection routes in your application.
Route::redirect('/old-route', '/new-route');
Route::get('posts/{postId}/comments/{commentId}', function
($postId, $commentId) {
return “Post ID: $postId, Comment ID: $commentId”;
}); Access: /post/1/comments/2
Output: Post ID: 1, Comment ID: 2
Optional Parameters
• You can define optional parameters by adding
a ? at the end of the parameter name and
assigning a default value.
• where method
• Convenience methods
Route::get('/user/{id}/{name}', function (string $id, string $name) {
// ...
})->whereNumber('id')->whereAlpha('name');
// Generating Redirects...
return redirect()->route('profile');
return to_route('profile');
Route Groups
• Share route attributes – With Controller
use App\Http\Controllers\OrderController;
Route::controller(OrderController::class)->group(function () {
Route::get('/orders/{id}', 'show');
Route::post('/orders', 'store');
});
MIDDLEWARE
What is a Middleware?
• A mechanism to process HTTP requests before
the business logic executes.
• Think of it as a series of "layers" HTTP requests
must pass through before they hit your
application.
– Each layer can examine the request and even
reject it entirely.
HTTP Middleware
• For example, Laravel includes a middleware
that verifies the user of your application is
authenticated.
– If the user is not authenticated, the middleware
will redirect the user to the login screen.
– However, if the user is authenticated, the
middleware will allow the request to proceed
further into the application.
Built-in Middleware
• In Laravel, middleware can be defined directly on a
route to apply additional functionality like
authentication, throttling, or other custom
middleware.
• auth is a built-in middleware provided by Laravel.
Route::get('/dashboard', function () {
return 'Welcome to your dashboard!';
})->middleware('auth');
Using Middleware in Route Groups
• Grouping Routes with Shared Middleware
– All routes in the group are protected by the auth middleware.
Route::middleware(['auth'])->group(function () {
Route::get('/profile', function () {
return 'User profile';
});
Route::get('/settings', function () {
return 'User settings';
});
});
Creating a Custom Middleware (1/2)
• Artisan command to create the custom
middleware
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class CheckAge
{
public function handle(Request $request, Closure $next)
{
// Middleware logic goes here
if ($request->age < 18) {
return redirect('home')->with('error', 'You are not old enough to
access this page.');
}
return $next($request);
}
}
Types of Middleware
• Global Middleware
• For tasks that should always run, no matter what
route is being accessed.
• Example: Enforcing SSL, adding security headers.
• Route based Middleware
– For tasks that should apply only to certain routes.
– Example: Protecting /dashboard with
authentication (auth middleware)
Global Middleware
• Create the middleware:
Effect:
php artisan make:middleware TrimInput
•All incoming requests will have their input
• Add logic in the middleware: values trimmed automatically.
•Example:
// app/Http/Middleware/TrimInput.php
• Input: name = " John Doe "
namespace App\Http\Middleware;
• Trimmed to: name = "John Doe"
use Closure;
class TrimInput
{
public function handle($request, Closure $next)
{
$request->merge(array_map('trim', $request->all())); // Trim all input values
return $next($request);
}
}
• Register it as global middleware in app/Http/Kernel.php:
protected $middleware = [
\App\Http\Middleware\TrimInput::class, // Add your middleware here
];
Rout-based Middleware
• Apply auth middleware to specific routes only to
authenticate users
Route::get('/dashboard', function () {
return 'Welcome to your dashboard!';
})->middleware('auth'); // Apply auth middleware
• Effect:
• The routes (/dashboard) will only be accessible to authenticated users.
• Unauthenticated users will be redirected to the login page.
CONTROLLERS
Controllers
• Object Oriented way to handle business logic
• Group together related requests in one class
• Add custom controllers in
app/Http/Controllers directory
php artisan make:controller TestController
Example: TestController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
}
Test View
Create /resources/views/test.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Test Page</title>
</head>
<body>
<h1>Welcome to the Test Page</h1>
<p>This is a simple test view.</p>
</body>
</html>
Set Route: TestController
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TestController;
• When you try to access test, you will receive the error
– Route [login] not defined.
• The error "Route [login] not defined" occurs because the
auth middleware is being applied to the route, but the login
route (where unauthenticated users are redirected) has not
been defined in your application.
What is happening?
• The auth middleware is used to protect the /test
route.
• When an unauthenticated user tries to access /test,
the middleware attempts to redirect them to the
login route.
• Since the login route is missing, Laravel throws the
error.
The simplest way to fix it…!
• Instead of manually defining the login route, you can
use Laravel's pre-built authentication scaffolding.
• Install Laravel Breeze (Simple Authentication):
composer require laravel/breeze --dev
php artisan breeze:install
npm install && npm run dev
php artisan migrate
• This will set up the login route and other basic
authentication routes.
Resource Controllers
• RESTful Resource Controllers
• API Resource Controllers
RESTful Resource Controllers
php artisan make:controller PhotoController --resource
app/Http/Controllers/PhotoController.php
use App\Http\Controllers\PhotoController;
Route::resource('photos', PhotoController::class);
Verb URI Action Route Name Purpose
GET /photos index photos.index Display all photos
GET /photos/create create photos.create Show a form to create a photo
POST /photos store photos.store Store a new photo
GET /photos/{photo} show photos.show Display a specific photo
GET /photos/{photo}/edit edit photos.edit Show a form to edit a photo
PUT/PATCH /photos/{photo} update photos.update Update a specific photo
DELETE /photos/{photo} destroy photos.destroy Delete a specific photo
Example: PhotoController.php
php artisan make:controller PhotoController --resource
A new controller file is created with predefined methods for CRUD operations.
class PhotoController extends Controller
{
public function index()
{
// Display a listing of the resource
}
app/Http/Controllers/PhotoController.php
use App\Http\Controllers\PhotoController;
use App\Http\Controllers\ProfileController;
use Illuminate\Support\Facades\Route;
Route::singleton('profile', ProfileController::class);
• cd
Deploy
project-name
• Access
– http://localhost:8000 (or)
– http://127.0.0.1:8000
Other methods to get started
• https://laravel.com/docs/10.x#laravel-and-doc
ker
More Laravel, Next Time!
QUESTIONS?