Table of Contents
? What is routing in Laravel?
? Key features of Laravel routing
? How to define routes in Laravel
Real-life example: simple blogging application?
View all posts ?
View individual posts ?
Add new post ?
Handling multiple HTTP methods?
Point route to controller ?
? Advanced routing features
Named route ?
Routing parameters?
Middleware in routing?
Routing group ?
Route model binding?
Test routing?
? Additional tips at the end of the article [Optimizing Laravel Routing]
? Conclusion
Home Backend Development PHP Tutorial Understanding Laravel&#s Routing System [Laravel beginner series | Part 2]

Understanding Laravel&#s Routing System [Laravel beginner series | Part 2]

Jan 28, 2025 am 04:07 AM

Understanding Laravel

? The second article in the Laravel newbie series is here! Let’s get straight to the point!

? What is routing in Laravel?

The routing mechanism in Laravel defines how the application responds to user requests. When a user visits a URL or submits a form, Laravel's routing system decides what to do next. This might include returning a view, performing controller actions, or processing data.

Laravel’s routing is handled in the routes folder, especially in files such as web.php and api.php.

? Key features of Laravel routing

  1. Simple and intuitive syntax: Laravel provides a straightforward way to define routes using its concise syntax.
  2. Supports various HTTP methods: Routing in Laravel can handle different HTTP methods such as GET, POST, PUT, DELETE, etc.
  3. Middleware integration: Middleware can be applied to routes for tasks such as authentication or logging.
  4. Named route: Named routes simplify URL generation and redirection within your application.
  5. Routing group: Grouping routes makes it easier to apply shared attributes such as middleware or prefixes.

? How to define routes in Laravel

The route for web requests is defined in the routes/web.php file, and the route for API requests is defined in the routes/api.php file.

<code>Route::get('/', function () {
    return view('welcome');
});</code>
Copy after login
Copy after login
  • Route::get: Specify the HTTP method.
  • /: URL visited by the user.
  • function (): callback function for processing requests.
  • view('welcome'): Returns the welcome.blade.php view.

Real-life example: simple blogging application?

Suppose you are building a blogging application where users can view a list of posts, view details of individual posts, and add new posts.

View all posts ?

Here, the /posts route gets the list of posts and passes them to the posts.index view.

<code>Route::get('/posts', function () {
    $posts = [
        ['id' => 1, 'title' => '第一篇文章', 'content' => '这是第一篇文章的内容。'],
        ['id' => 2, 'title' => '第二篇文章', 'content' => '这是第二篇文章的内容。']
    ];

    return view('posts.index', ['posts' => $posts]);
});</code>
Copy after login
Copy after login

View individual posts ?

Here, the /posts/{id} route dynamically gets the post by ID and returns the detailed view. Show Laravel's default 404 error if the post does not exist.

<code>Route::get('/posts/{id}', function ($id) {
    $posts = [
        1 => ['title' => '第一篇文章', 'content' => '这是第一篇文章的内容。'],
        2 => ['title' => '第二篇文章', 'content' => '这是第二篇文章的内容。']
    ];

    if (!isset($posts[$id])) {
        abort(404, '帖子未找到');
    }

    return view('posts.show', ['post' => $posts[$id]]);
});</code>
Copy after login
Copy after login

Add new post ?

The

/posts route handles form submissions for adding new posts.

<code>Route::post('/posts', function () {
    // 添加新帖子的逻辑
    return '已添加新帖子!';
});</code>
Copy after login
Copy after login

Handling multiple HTTP methods?

Laravel provides various methods to define routes for different HTTP verbs.

<code>Route::post('/submit', function () {
    return '表单已提交!';
});

Route::put('/update', function () {
    return '数据已更新!';
});

Route::delete('/delete', function () {
    return '数据已删除!';
});</code>
Copy after login

Point route to controller ?

Using controllers helps keep routing files simple and easy to maintain. Here, UserController@index handles the logic of the /users route.

<code>Route::get('/users', [UserController::class, 'index']);</code>
Copy after login

? Advanced routing features

Named route ?

Named routes allow you to reference routes by name instead of URL, which is especially useful when the URL changes.

<code>Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');</code>
Copy after login

You can then generate the URL for this route:

<code>$url = route('dashboard');</code>
Copy after login

Routing parameters?

You can pass dynamic parameters in routes.

Required parameters

<code>Route::get('/user/{id}', function ($id) {
    return '用户ID:' . $id;
});</code>
Copy after login

Optional parameters

<code>Route::get('/', function () {
    return view('welcome');
});</code>
Copy after login
Copy after login

Middleware in routing?

Middleware can restrict access or perform operations before processing the request.

<code>Route::get('/posts', function () {
    $posts = [
        ['id' => 1, 'title' => '第一篇文章', 'content' => '这是第一篇文章的内容。'],
        ['id' => 2, 'title' => '第二篇文章', 'content' => '这是第二篇文章的内容。']
    ];

    return view('posts.index', ['posts' => $posts]);
});</code>
Copy after login
Copy after login

In this example, only authenticated users can access the /profile route.

Routing group ?

Route groups allow you to apply shared properties such as middleware or prefixes. Here, all routes within the group share the admin prefix and auth middleware.

<code>Route::get('/posts/{id}', function ($id) {
    $posts = [
        1 => ['title' => '第一篇文章', 'content' => '这是第一篇文章的内容。'],
        2 => ['title' => '第二篇文章', 'content' => '这是第二篇文章的内容。']
    ];

    if (!isset($posts[$id])) {
        abort(404, '帖子未找到');
    }

    return view('posts.show', ['post' => $posts[$id]]);
});</code>
Copy after login
Copy after login

Route model binding?

Laravel can automatically bind routing parameters to Eloquent models. In this case, Laravel retrieves the Post model corresponding to the {post} parameter.

Test routing?

Laravel easily tests routes using its built-in tools. You can use php artisan route:list to view all defined routes in your application. This command displays details such as routing method, URI, and assigned middleware.

<code>Route::post('/posts', function () {
    // 添加新帖子的逻辑
    return '已添加新帖子!';
});</code>
Copy after login
Copy after login

? Additional tips at the end of the article [Optimizing Laravel Routing]

  1. Use route cache: cache your routes to improve performance in production php artisan route:list.
  2. Avoid route overload: keep routes simple and delegate complex logic to controllers or middleware.
  3. Group related routes: Use route groups to simplify code and apply common functionality.

? Conclusion

Laravel's routing system is a powerful and flexible tool that simplifies web development. By understanding the basics and taking advantage of advanced features such as middleware, named routing, and routing model binding, you can create applications that are concise, efficient, and easy to maintain.

Laravel has great and very well done documentation here.

PS: If you found this post helpful, please like and share it! If you have any questions for me, please leave a message! I'd love to chat with you! :)

Our next article will be out next week!

The above is the detailed content of Understanding Laravel&#s Routing System [Laravel beginner series | Part 2]. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles