


Understanding Laravels Routing System [Laravel beginner series | Part 2]
? 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
- Simple and intuitive syntax: Laravel provides a straightforward way to define routes using its concise syntax.
- Supports various HTTP methods: Routing in Laravel can handle different HTTP methods such as GET, POST, PUT, DELETE, etc.
- Middleware integration: Middleware can be applied to routes for tasks such as authentication or logging.
- Named route: Named routes simplify URL generation and redirection within your application.
- 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]
- Use route cache: cache your routes to improve performance in production php artisan route:list.
- Avoid route overload: keep routes simple and delegate complex logic to controllers or middleware.
- 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 Laravels Routing System [Laravel beginner series | Part 2]. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

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,

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? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

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

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.

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�...
