


Understanding Laravels Routing System [Laravel beginner series | Part 2]
Jan 28, 2025 am 04:07 AM? 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' => '這是第一篇文章的內(nèi)容。'], ['id' => 2, 'title' => '第二篇文章', 'content' => '這是第二篇文章的內(nèi)容。'] ]; 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' => '這是第一篇文章的內(nèi)容。'], 2 => ['title' => '第二篇文章', 'content' => '這是第二篇文章的內(nèi)容。'] ]; 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 '數(shù)據(jù)已更新!'; }); Route::delete('/delete', function () { return '數(shù)據(jù)已刪除!'; });</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' => '這是第一篇文章的內(nèi)容。'], ['id' => 2, 'title' => '第二篇文章', 'content' => '這是第二篇文章的內(nèi)容。'] ]; 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' => '這是第一篇文章的內(nèi)容。'], 2 => ['title' => '第二篇文章', 'content' => '這是第二篇文章的內(nèi)容。'] ]; 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

Undress AI Tool
Undress images for free

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

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

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

ToversionaPHP-basedAPIeffectively,useURL-basedversioningforclarityandeaseofrouting,separateversionedcodetoavoidconflicts,deprecateoldversionswithclearcommunication,andconsidercustomheadersonlywhennecessary.StartbyplacingtheversionintheURL(e.g.,/api/v

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

Proceduralandobject-orientedprogramming(OOP)inPHPdiffersignificantlyinstructure,reusability,anddatahandling.1.Proceduralprogrammingusesfunctionsorganizedsequentially,suitableforsmallscripts.2.OOPorganizescodeintoclassesandobjects,modelingreal-worlden

PHPdoesnothaveabuilt-inWeakMapbutoffersWeakReferenceforsimilarfunctionality.1.WeakReferenceallowsholdingreferenceswithoutpreventinggarbagecollection.2.Itisusefulforcaching,eventlisteners,andmetadatawithoutaffectingobjectlifecycles.3.YoucansimulateaWe

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.
