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]

Patricia Arquette
Patricia ArquetteOriginal
2025-01-28 04:07:36442browse

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>
  • 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>

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>

Add new post ?

The

/posts route handles form submissions for adding new posts.

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

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>

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>

? 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>

You can then generate the URL for this route:

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

Routing parameters?

You can pass dynamic parameters in routes.

Required parameters

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

Optional parameters

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

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>

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>

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>

? 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:
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