Unit 2 - Notes
Unit 2: Request, Routing & Responses
1. Laravel Request Lifecycle
The Request Lifecycle describes the journey of an HTTP request from the moment it enters the application until the response is sent back to the user. Understanding this is crucial for understanding how Laravel creates the "structure" of the application.
Key Stages of the Lifecycle
-
Entry Point (
public/index.php):- All requests are directed to
public/index.phpby the web server (Apache/Nginx). - This file loads the Composer generated autoloader definition.
- It retrieves an instance of the Laravel application from
bootstrap/app.php.
- All requests are directed to
-
HTTP / Console Kernels:
- The incoming request is sent to either the HTTP Kernel or the Console Kernel (depending on the interface).
- The HTTP Kernel (
app/Http/Kernel.php):- Defines the list of middleware that the request must pass through before being handled (e.g., Session handling, CSRF protection, Maintenance mode).
- Performs bootstrapping actions (configuring error handling, logging, etc.).
-
Service Providers:
- This is the most important part of the booting process.
- Found in
config/app.php. - Register Phase: All service providers register bindings into the Service Container.
- Boot Phase: Once all providers are registered, the
bootmethod is called on all providers. This is where event listeners, routes, and middleware are often registered.
-
Routing:
- Once the application is bootstrapped, the request is handed to the Router.
- The router dispatches the request to a route or controller.
- It also runs any route-specific middleware.
-
Controller / Method:
- If the route directs to a controller, the specific action method is executed.
- This method performs the business logic (fetching data, processing input).
-
Response:
- The controller returns a response (usually a View or JSON).
- The response travels back through the middleware (outbound) allowing modification of headers or content.
- Finally, the
index.phpfile sends the response to the user's browser.
2. Basic Routing
Routes define how the application responds to a client request to a specific URI. In Laravel, web routes are defined in routes/web.php.
Basic Route Definition
The simplest route consists of a URI and a Closure (anonymous function).
use Illuminate\Support\Facades\Route;
// GET Request
Route::get('/greeting', function () {
return 'Hello World';
});
// POST Request
Route::post('/submit', function () {
// Handle form submission
});
Available Router Methods
Laravel provides methods for all HTTP verbs:
Route::get(callback);Route::post(callback);Route::put(callback);Route::patch(callback);Route::delete(callback);Route::options(callback);
Route Match and Any
Sometimes a route needs to handle multiple HTTP verbs:
// Match specific verbs
Route::match(['get', 'post'], '/', function () {
// ...
});
// Match any verb
Route::any('/', function () {
// ...
});
3. Routing Parameters
Routes often need to capture segments of the URI (e.g., a user ID or a post slug).
Required Parameters
Parameters are enclosed in curly braces {} and passed to the callback/controller.
Route::get('/user/{id}', function ($id) {
return 'User ID: ' . $id;
});
Note: Route parameters are injected into route callbacks based on their order.
Optional Parameters
To make a parameter optional, append a ? to the parameter name and ensure the variable has a default value.
Route::get('/user/{name?}', function ($name = 'Guest') {
return 'User Name: ' . $name;
});
Regular Expression Constraints
You can restrict the format of route parameters using the where method.
// Only allow numeric IDs
Route::get('/user/{id}', function ($id) {
// ...
})->where('id', '[0-9]+');
// Helper methods
Route::get('/user/{id}', ...)->whereNumber('id');
Route::get('/user/{name}', ...)->whereAlpha('name');
4. Understanding Views in Laravel
Views separate the controller logic/domain logic from the presentation logic (HTML). Views are the "V" in MVC.
- Location:
resources/views. - File Extension:
.blade.php(if using the Blade templating engine) or.php. - Blade Engine: Laravel's powerful templating engine that compiles views into plain PHP code for performance.
Creating a View
File: resources/views/greeting.blade.php
<html>
<body>
<h1>Hello, World</h1>
</body>
</html>
Rendering a View
Views are returned from routes or controllers using the global view helper.
Route::get('/', function () {
// Looks for resources/views/greeting.blade.php
return view('greeting');
});
5. Passing Data to Views
Views often require dynamic data from the controller.
Method 1: Using an Array
Pass an associative array as the second argument to the view helper.
Route::get('/', function () {
return view('greeting', ['name' => 'James', 'age' => 25]);
});
Inside the view, you access these as variables:
age.
Method 2: Using the with Method
Chain the with method to the view factory.
return view('greeting')
->with('name', 'James')
->with('age', 25);
Method 3: Using compact (PHP Function)
This is the most common and cleanest method when variable names match key names.
$name = 'James';
$age = 25;
return view('greeting', compact('name', 'age'));
6. Sharing Data with all Views
Sometimes, specific data (like navigation menus, site settings, or the authenticated user) needs to be accessible by every view in the application, so you don't have to pass it manually in every controller method.
Implementation
This is typically done in the boot method of a Service Provider (usually App\Providers\AppServiceProvider).
namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
// Share data with all views
View::share('siteName', 'My Awesome App');
}
}
Now, the
$siteName variable is available in every blade file.
7. Laravel Response
When a route or controller is executed, it must return a response to the browser.
Basic Responses
- Strings: Laravel automatically converts strings to a full HTTP response.
- Arrays: Laravel automatically converts arrays to JSON responses.
The Response Object
For more control (headers, cookies), use the Illuminate\Http\Response instance.
Route::get('/home', function () {
return response('Hello World', 200);
});
Attaching Headers
Headers can be added using the header method.
return response('Hello World')
->header('Content-Type', 'text/plain')
->header('X-Header-One', 'Header Value');
Attaching Cookies
Cookies can be added using the cookie method.
return response('Hello World')
->cookie('name', 'value', $minutes);
JSON Response
The json method sets the Content-Type header to application/json and encodes the array.
return response()->json([
'name' => 'Abigail',
'state' => 'CA',
]);
8. Laravel Redirections
Redirects are responses that send the user to a different URL.
Basic Redirection
Use the global redirect helper.
Route::get('/dashboard', function () {
return redirect('/home/dashboard');
});
Redirecting to Named Routes
When a route has a name assigned to it, you can redirect specifically to that route name. This is preferred over hardcoding URLs because if the URL changes, the redirect logic remains valid.
Defining the Name:
Route::get('/user/profile', function () {
// ...
})->name('profile');
Redirecting:
return redirect()->route('profile');
With Parameters:
// For route: /user/{id}/profile
return redirect()->route('profile', ['id' => 1]);
Redirecting to Controller Actions
You can redirect to a specific controller method.
use App\Http\Controllers\UserController;
return redirect()->action([UserController::class, 'index']);
With Parameters:
return redirect()->action(
[UserController::class, 'show'], ['id' => 1]
);
Redirect with Flash Data
Redirecting often happens after a form submission. You can flash data to the session (available for only the next request) using with.
Route::post('/user/profile', function () {
// Update user...
return redirect('dashboard')->with('status', 'Profile updated!');
});
In the view, check
session('status') to display the message.