search
HomePHP FrameworkLaravelLaravel Lecture 3: Global constraints on routing parameters, routing redirection and routing view binding

A previous article has already explained some knowledge about routing, and I will continue to add a few points today.

Global constraints of routing parameters

We already know that we can use the where method to constrain parameters, as follows:

Route::get('news/{id}', function ($id)
{
    echo 'news:' . $id;
})->where('id', '[0-9]+');

Route::get('list/{id}', function ($id)
{
    echo 'list:' . $id;
})->where('id', '[0-9]+');

About This ID is used by multiple routes and the constraints are the same. Then, we can constrain ids on a global scale. In this way, local routing does not need to be constrained, and the code will not be redundant.

Now, let’s edit the boot method in app/Providers/RouteServiceProvider.php and add a line of code, as follows:

public function boot()
 {
     Route::pattern('id', '[0-9]+');
     parent::boot();
 }

Once defined, these rules will be automatically applied to all on the route using this parameter name. But if I want to cancel this restriction or reset parameter rules on individual routes, how should I do it?

To reset, just reset the rules in the where method

Route::get('news/{id}', function ($id)
{
    echo 'news:' . $id;
})->where('id', '[a-z]');

The method to cancel the restriction is actually to reset the rules, but use .* in the rules to regularize any characters

Route::get('news/{id}', function ($id)
{
    echo 'news:' . $id;
})->where('id', '.*');

Route redirection

We can jump from one route to another address or another route, just use the redirect method of Route

// 跳转到php中文网
Route::redirect('index', ' 

// 跳转到本站另一个路由
Route::redirect('a', 'news/1');

The default route redirection uses 302 temporary redirection. If you want to set up a 301 permanent redirection, you need to set the third parameter or use another method, which is permanentRedirect.

Route::redirect('b', 'news/1', 301);
Route::permanentRedirect('c', 'news/2');

Routing and view binding

Routing can also be directly bound to the view without going through the controller. Here we need to use the view method, which has three parameters: uri (required parameters), view name (required parameters), and parameters (optional parameters).

Route::view('vtest', 'view1', ['str' => 'study laravel']);

Now let’s create a view file named view1 and create a view1.blade.php file in the resources/views directory. The content of the file is as follows:

view1{{$str}}

In addition to using Route::view In addition, you can also use the global view function in the closure of get or other methods to achieve the same effect.

Route::get('vtest', function ()
{
    return view('view1', ['str' => 'study laravel2']);
});

The above is the detailed content of Laravel Lecture 3: Global constraints on routing parameters, routing redirection and routing view binding. 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
Beyond the Zoom Call: Creative Strategies for Connecting Distributed TeamsBeyond the Zoom Call: Creative Strategies for Connecting Distributed TeamsApr 26, 2025 am 12:24 AM

ToenhanceengagementandcohesionamongdistributedteamsbeyondZoom,implementthesestrategies:1)Organizevirtualcoffeebreaksforinformalchats,2)UseasynchronoustoolslikeSlackfornon-workdiscussions,3)Introducegamificationwithteamgamesorchallenges,and4)Encourage

What are the breaking changes in the latest Laravel version?What are the breaking changes in the latest Laravel version?Apr 26, 2025 am 12:23 AM

Laravel10introducesseveralbreakingchanges:1)ItrequiresPHP8.1orhigher,2)TheRouteServiceProvidernowusesabootmethodforloadingroutes,3)ThewithTimestamps()methodonEloquentrelationshipsisdeprecated,and4)TheRequestclassnowpreferstherules()methodforvalidatio

The Productivity Paradox: Maintaining Focus and Motivation in Remote SettingsThe Productivity Paradox: Maintaining Focus and Motivation in Remote SettingsApr 26, 2025 am 12:17 AM

Tomaintainfocusandmotivationinremotework,createastructuredenvironment,managedigitaldistractions,fostermotivationthroughsocialinteractionsandgoalsetting,maintainwork-lifebalance,anduseappropriatetechnology.1)Setupadedicatedworkspaceandsticktoaroutine.

Building Trust from Afar: Fostering Collaboration in Distributed EnvironmentsBuilding Trust from Afar: Fostering Collaboration in Distributed EnvironmentsApr 26, 2025 am 12:13 AM

Tofostercollaborationandtrustinremoteteams,implementthesestrategies:1)Establishregular,structuredcommunicationwithpersonalcheck-ins,2)Usecollaborativetoolsfortransparency,3)Recognizeandcelebrateachievements,and4)Fosteracultureoftrustandadaptability.

What are the key features of the latest Laravel version?What are the key features of the latest Laravel version?Apr 26, 2025 am 12:01 AM

Laravel's latest version of the main features include: 1. LaravelOctane improves application performance, 2. Improved model factory support relationships and state definitions, 3. Enhanced Artisan commands, 4. Improved error handling, 5. New Eloquent accessors and modifiers. These features significantly improve development efficiency and application performance, but need to be used with caution to avoid potential problems.

The Illusion of Inclusion: Addressing Isolation and Loneliness in Remote WorkThe Illusion of Inclusion: Addressing Isolation and Loneliness in Remote WorkApr 25, 2025 am 12:28 AM

Tocombatisolationandlonelinessinremotework,companiesshouldimplementregular,meaningfulinteractions,provideequalgrowthopportunities,andusetechnologyeffectively.1)Fostergenuineconnectionsthroughvirtualcoffeebreaksandpersonalsharing.2)Ensureremoteworkers

Laravel for Full-Stack Development: A Comprehensive GuideLaravel for Full-Stack Development: A Comprehensive GuideApr 25, 2025 am 12:27 AM

Laravelispopularforfull-stackdevelopmentbecauseitoffersaseamlessblendofbackendpowerandfrontendflexibility.1)Itsbackendcapabilities,likeEloquentORM,simplifydatabaseinteractions.2)TheBladetemplatingengineallowsforclean,dynamicHTMLtemplates.3)LaravelMix

Video Conferencing Showdown: Choosing the Right Platform for Remote MeetingsVideo Conferencing Showdown: Choosing the Right Platform for Remote MeetingsApr 25, 2025 am 12:26 AM

Key factors in choosing a video conferencing platform include user interface, security, and functionality. 1) The user interface should be intuitive, such as Zoom. 2) Security needs to be paid attention to, and Microsoft Teams provides end-to-end encryption. 3) Functions need to match requirements, GoogleMeet is suitable for short meetings, and CiscoWebex provides advanced collaboration tools.

See all articles

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!