Learn Laravel · 2/17

Routing & Responses: The Traffic Director

5 min read

Routing & Responses: The Traffic Director 🚦

Welcome, future Laravel artisan! Today, we're diving into one of the most fundamental concepts of any web application: Routing.

What is Routing?

At its core, routing is the process of mapping a URL (the web address you type in your browser) to a specific piece of code in your application that should handle the request. Think of it as the friendly traffic director for your web app. When a user visits a specific URL, the router decides which part of your code gets to work.

The Problem It Solves

Imagine a massive library without a catalog system. Finding a specific book would be a nightmare! Similarly, without routing, your application wouldn't know how to respond to different user requests. A request for /home should show the homepage, while a request for /profile should display a user's profile. Routing provides this essential mapping.


Basic Routing: Handling GET and POST Requests 📬

Let's start with the bread and butter of web requests: GET and POST.

  • GET requests are typically used to retrieve data. When you visit a website, your browser sends a GET request.
  • POST requests are used to send data to the server, like when you submit a form.

In Laravel, you define your routes in the routes/web.php file for web-based requests.

Example: A Simple GET Request

Let's create a route that displays a welcome message.

php
// routes/web.php

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return 'Hello, World!';
});

Here, we're telling Laravel: "When a user makes a GET request to the homepage (/), execute this function and return the string 'Hello, World!'." Simple, right?

Example: Handling a POST Request

Now, let's handle a form submission. Imagine a simple contact form.

php
// routes/web.php

Route::post('/contact', function () {
    // Process the form data here
    return 'Your message has been sent!';
});

This route listens for POST requests to the /contact URL. When a form is submitted to this URL, the enclosed function will be executed.

Funny Exaggeration: Without POST routes, every time you tried to submit a form, it would be like shouting your credit card details across a crowded room. Not very secure! POST keeps that information neatly contained.


Dynamic Paths: Route Parameters and Wildcards 🃏

What if you want to create a profile page for each user? You wouldn't want to create a separate route for every single user, like /users/john and /users/jane. That would be chaos! This is where dynamic paths come in.

Route parameters allow you to capture segments of the URL. These are defined by curly braces {}.

Example: A Dynamic User Profile Route

php
// routes/web.php

Route::get('/users/{id}', function ($id) {
    return 'Showing user with ID: ' . $id;
});

Now, if a user visits /users/1, the output will be "Showing user with ID: 1". If they visit /users/123, it will be "Showing user with ID: 123". The $id variable in the function automatically captures the value from the URL.

Wildcards: The "Catch-All"

Sometimes you need a route to catch a wider range of URLs. While not a default feature, you can use regular expression constraints to create a wildcard.

php
// routes/web.php

Route::get('/pages/{slug}', function ($slug) {
    return 'Displaying page: ' . $slug;
})->where('slug', '.*');

This tells Laravel that the {slug} parameter can be any sequence of characters.


Organization is Key: Named Routes and Route Groups 🗂️

As your application grows, you'll have more and more routes. Keeping them organized is crucial for maintainability.

Named Routes: Giving Your Routes a Nickname

You can give a name to a route, which makes it easier to reference elsewhere in your application, like when generating URLs in your views.

Example: Naming a Route

php
// routes/web.php

Route::get('/admin/dashboard', function () {
    return 'Welcome to the admin dashboard!';
})->name('admin.dashboard');

Now, instead of hardcoding the URL /admin/dashboard, you can simply refer to it by its name, admin.dashboard.

Route Groups: Bundling Routes Together

Route groups allow you to apply attributes like prefixes or middleware to a group of routes, reducing code duplication.

Example: Using a Route Group

Imagine you have several routes that start with /admin. Instead of typing /admin for each one, you can group them:

php
// routes/web.php

Route::prefix('admin')->group(function () {
    Route::get('/dashboard', function () {
        // Matches The "/admin/dashboard" URL
    })->name('dashboard');

    Route::get('/users', function () {
        // Matches The "/admin/users" URL
    })->name('users');
});

You can even group by name to keep your naming consistent.

php
// routes/web.php

Route::name('admin.')->prefix('admin')->group(function () {
    Route::get('/dashboard', function () {
        // Route assigned name "admin.dashboard"
    })->name('dashboard');

    Route::get('/users', function () {
        // Route assigned name "admin.users"
    })->name('users');
});

Sending Stuff Back: Views, JSON, and Redirects 📤

A route's job isn't just to receive a request; it also needs to send a response. Laravel provides several ways to do this.

Returning a View

Most of the time, you'll want to return an HTML view to the user. The view() helper function makes this easy.

php
// routes/web.php

Route::get('/', function () {
    return view('welcome');
});

This will render the welcome.blade.php file located in your resources/views directory.

You can also pass data to your views.

php
// routes/web.php

Route::get('/greeting', function () {
    return view('greeting', ['name' => 'John']);
});

Returning JSON

For APIs or when working with JavaScript frameworks, you'll often need to return data in JSON format. Laravel automatically converts arrays and Eloquent collections to JSON.

php
// routes/web.php

Route::get('/api/users', function () {
    return [
        ['id' => 1, 'name' => 'Alice'],
        ['id' => 2, 'name' => 'Bob'],
    ];
});

Redirecting the User

Sometimes, you need to send the user to a different URL. The redirect() helper is your friend here.

Example: Redirecting to a Named Route

php
// routes/web.php

Route::post('/profile/update', function () {
    // Update the user's profile...

    return redirect()->route('profile.show');
});

Route::get('/profile', function () {
    // Show the user's profile
})->name('profile.show');

After a user updates their profile (a POST request), we redirect them back to their profile page (a GET request). This is a common pattern known as Post/Redirect/Get (PRG) and it prevents the user from accidentally resubmitting the form by refreshing the page.


📚 References for Extra Reading:

Challenge

You are building the routing for an admin panel's blog management feature. Your task is to define all the necessary routes within a single route group in your routes/web.php file.

Requirements:

  1. Create a route group that applies the following attributes to all nested routes:

    • A URL prefix of admin.
    • A name prefix of admin..
  2. Inside this group, define the following five routes for handling blog posts:

    • List Posts: A GET route to /posts that returns the admin.posts.index view. This route should be named posts.index.
    • Show Create Form: A GET route to /posts/create that returns the admin.posts.create view. This route should be named posts.create.
    • Store New Post: A POST route to /posts that handles the form submission for creating a new post. This route should be named posts.store. After processing, it should redirect to the route responsible for showing a single post. For this challenge, assume the newly created post has an ID of 123.
    • Show Single Post: A GET route that uses a route parameter named post (e.g., /posts/{post}). This route should be named posts.show and must return the post's data as a JSON response. The callback function should accept the post ID from the URL.
    • Show Edit Form: A GET route to /posts/{post}/edit that returns the admin.posts.edit view. This route should be named posts.edit.

Expected result

The solution should contain a single Route::group definition chaining the prefix() and name() methods.

  • The group must be configured with prefix('admin') and name('admin.').
  • Inside the group's callback function, there must be five distinct route definitions:
  1. Route::get('posts', ...)->name('posts.index');
    • The callback should return view('admin.posts.index');.
  2. Route::get('posts/create', ...)->name('posts.create');
    • The callback should return view('admin.posts.create');.
  3. Route::post('posts', ...)->name('posts.store');
    • The callback must return a redirect to the fully-qualified named route admin.posts.show, passing 123 as the post parameter. The correct syntax is redirect()->route('admin.posts.show', ['post' => 123]);.
  4. Route::get('posts/{post}', function ($post) { ... })->name('posts.show');
    • The callback must accept the $post parameter.
    • It should return any valid array, which Laravel will automatically convert to JSON. For example: ['id' => $post, 'title' => 'A Post Title'];.
  5. Route::get('posts/{post}/edit', ...)->name('posts.edit');
    • The callback should return view('admin.posts.edit');.
php

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.