search
HomePHP FrameworkLaravellaravel has several routes

laravel has several routes

Sep 02, 2021 pm 12:11 PM
laravelrouting

Laravel has 6 types of routes: 1. get, the syntax "Route::get($uri,$callback)"; 2. post, the syntax "Route::post($uri,$callback)"; 3. put, the syntax "Route::put($uri, $callback)"; 4. patch, the syntax "Route::patch($uri, $callback)"; 5. delete, the syntax "Route::delete($ uri, $callback)"; 6. options, syntax "Route::options($uri, $callback)".

laravel has several routes

The operating environment of this tutorial: Windows 7 system, Laravel 6 version, DELL G3 computer.

What are the common routes in Laravel

Summary in one sentence:

6 types: post, get, put, patch, delete, options

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);

1. What is the security measure of Lararel's CSRF protection form?

Function: Laravel provides a simple way to protect your application from Cross-site request forgery (CSRF) attacks. Cross-site request forgery is a malicious attack that leverages the identity of an authenticated user to run unauthorized commands.

Implementation: Add the following sentence to the form: {{csrf_field()}}. See the code

for details. The essence is: adding a token value to the form; input type="hidden" name="_token" value="SqlDhf...a string of random characters String "

The principle is: Check whether the token value of the form is legal, if it is legal, it will pass, otherwise it will not pass

<form method="POST" action="/profile">
    {{ csrf_field() }}
    ...
</form>

2. How to write the post request method in routing?

is the post method: Route::post('check',"LoginController@check");

3. How to implement the put request in routing?

Route writing method: Route's put method: Route::put('put','LoginController@put');

Controller writing method: This is the writing method of the basic controller

The request page sets the request type to put: input type="hidden" name="_method" value="put"

Writing in routing

// put请求

Route::get(&#39;putWeb&#39;,&#39;LoginController@putWeb&#39;);

// put的处理页面
Route::put(&#39;put&#39;,&#39;LoginController@put&#39;);

Controller writing

// put请求页面

public function putWeb(){

    return view(&#39;putWeb&#39;);
}

// put请求处理页面
public function put(Request $request){
    dd($request->input());
}

Request page writing

<form action="put" method="post">
    <p>
        {{csrf_field()}}

        <input type="hidden" name="_method" value="put">
        User:
        <input type="text" name="user" id="">
    </p>
</form>

4. How can one page in Laravel implement multiple request methods (I can get the page data, and the user can use the search box to post requests)?

match (specified request) :Route::match(['get','post'],'/',"IndexController@index ");

Controller code:Determine whether the user is making a post request, if so, output the user's search, otherwise output the data normally displayed on the page

any (all requests) :Route::any('/',"IndexController@index");

5, Laravel Usage examples and implementation of resource routing (more commonly used in actual projects)?

Example: There are many modules in the background, User module, management module, etc. (add, delete, modify, check): Write it directly in the routing A lot of trouble

Route::get(&#39;user/index&#39;,&#39;UserController@index&#39;);
Route::get(&#39;user/add&#39;,&#39;UserController@add&#39;);
Route::get(&#39;user/edit&#39;,&#39;UserController@edit&#39;);
Route::post(&#39;user/insert&#39;,&#39;UserController@insert&#39;);
Route::post(&#39;user/update&#39;,&#39;UserController@update&#39;);
Route::get(&#39;user/del&#39;,&#39;UserController@del&#39;);

Implementation: resource method: Route::resource('Admin','IndexController');

| GET|HEAD  | Admin              | Admin.index   | App\Http\Controllers\IndexController@index   | web          | #展示页面

| POST      | Admin              | Admin.store   | App\Http\Controllers\IndexController@store   | web          | #添加操作

| GET|HEAD  | Admin/create       | Admin.create  | App\Http\Controllers\IndexController@create  | web          | #添加页面

| DELETE    | Admin/{Admin}      | Admin.destroy | App\Http\Controllers\IndexController@destroy | web          | #删除操作

| PUT|PATCH | Admin/{Admin}      | Admin.update  | 
App\Http\Controllers\IndexController@update  | web          | #更新操作

| GET|HEAD  | Admin/{Admin}      | Admin.show    | App\Http\Controllers\IndexController@show    | web          |

| GET|HEAD  | Admin/{Admin}/edit | Admin.edit    | App\Http\Controllers\IndexController@edit    | web          | #修改页面

| GET|HEAD  | api/user           |               | Closure                                      | api,auth:api |

6. How to take parameters and multiple parameters in routing?

Parameters in braces: Route::get('user/del/{id}',function($ id){ echo $id##; });

Multiple parameters: Route::get('UserInfo/

{name}/{sex}',function($name,$sex){ echo $name; echo $ sex; });

Parameters that may or may not be included:

Question mark default value:Route::get('user/ edit/{id?}',function($id="default value"){ echo $id; }); : With a default value, it is guaranteed to have a value when there are no parameters.

7. How to access the parameters in the route in the controller?

Directly pass in the parameters, there is no value in $_GET

Route::get(&#39;UserInfo/{name}/{sex}&#39;,"IndexController@UserInfo");

// 新建UserInfo
public function UserInfo($a,$sex1){
  var_dump($a);
  var_dump($sex1);
}

8、命名路由是什么以及作用?

是什么:就是给路由命名

实现:Route::get('abc',"IndexController@abc")->name('one');

作用:获取别名的url地址:控制器中:route('one');可以到以one为别名的控制器中

作用:通过命名路由实现重定向(实现重定向的一种方式):控制器中:return redirect()->route('one');

9、路由组命名空间的作用以及实现?

实现前后台控制器分离:需要在控制器目录下新建Admin目录和Home目录 在目录中新建控制器

在Route的group方法指定命名空间:Route::group(['namespace'=>'Admin'],function(){

在Admin中的控制器要写好命名空间,并且继承控制器要use到控制器

//路由中代码
Route::group([&#39;namespace&#39;=>&#39;Admin&#39;],function(){
    Route::get(&#39;admin&#39;,&#39;IndexController@index&#39;);
    Route::get(&#39;admin/user&#39;,&#39;UserController@index&#39;);
    Route::get(&#39;admin/goods&#39;,&#39;GoodsController@index&#39;);
});

Route::group([&#39;namespace&#39;=>&#39;Home&#39;],function(){
    Route::get(&#39;/&#39;,&#39;IndexController@index&#39;);
});
#需要在控制器目录下新建Admin目录和Home目录 在目录中新建控制器
#注意 需要修改命名空间

控制器中代码
<?php

    namespace App\Http\Controllers\Admin;

    use Illuminate\Http\Request;

    use DB;

    use App\Http\Controllers\Controller;

    class UserController extends Controller
    {
        //index 方法

        public function index(){

            echo "我是后台控制器User";
        }

    }

相关推荐:最新的五个Laravel视频教程

The above is the detailed content of laravel has several routes. 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
Last Laravel version: Migration TutorialLast Laravel version: Migration TutorialMay 14, 2025 am 12:17 AM

What new features and best practices does Laravel's migration system offer in the latest version? 1. Added nullableMorphs() for polymorphic relationships. 2. The after() method is introduced to specify the column order. 3. Emphasize handling of foreign key constraints to avoid orphaned records. 4. It is recommended to optimize performance, such as adding indexes appropriately. 5. Advocate the idempotence of migration and the use of descriptive names.

What is the Latest LTS Version of Laravel?What is the Latest LTS Version of Laravel?May 14, 2025 am 12:14 AM

Laravel10,releasedinFebruary2023,isthelatestLTSversion,supportedforthreeyears.ItrequiresPHP8.1 ,enhancesLaravelPennantforfeatureflags,improveserrorhandling,refinesdocumentation,andoptimizesperformance,particularlyinEloquentORM.

Stay Updated: The Newest Features in the Latest Laravel VersionStay Updated: The Newest Features in the Latest Laravel VersionMay 14, 2025 am 12:10 AM

Laravel's latest version introduces multiple new features: 1. LaravelPennant is used to manage function flags, allowing new features to be released in stages; 2. LaravelReverb simplifies the implementation of real-time functions, such as real-time comments; 3. LaravelVite accelerates the front-end construction process; 4. The new model factory system enhances the creation of test data; 5. Improves the error handling mechanism and provides more flexible error page customization options.

Implementing Soft Delete in Laravel: A Step-by-Step TutorialImplementing Soft Delete in Laravel: A Step-by-Step TutorialMay 14, 2025 am 12:02 AM

Softleteinelelavelisling -Memptry-braceChortsDevetus -TeedeecetovedinglyDeveledTeecetteecedelave

Current Laravel Version: Check the Latest Release and UpdatesCurrent Laravel Version: Check the Latest Release and UpdatesMay 14, 2025 am 12:01 AM

Laravel10.xisthecurrentversion,offeringnewfeatureslikeenumsupportinEloquentmodelsandimprovedroutemodelbindingwithenums.Theseupdatesenhancecodereadabilityandsecurity,butrequirecarefulplanningandincrementalimplementationforasuccessfulupgrade.

How to Use Laravel Migrations: A Step-by-Step TutorialHow to Use Laravel Migrations: A Step-by-Step TutorialMay 13, 2025 am 12:15 AM

LaravelmigrationsstreamlinedatabasemanagementbyallowingschemachangestobedefinedinPHPcode,whichcanbeversion-controlledandshared.Here'showtousethem:1)Createmigrationclassestodefineoperationslikecreatingormodifyingtables.2)Usethe'phpartisanmigrate'comma

Finding the Latest Laravel Version: A Quick and Easy GuideFinding the Latest Laravel Version: A Quick and Easy GuideMay 13, 2025 am 12:13 AM

To find the latest version of Laravel, you can visit the official website laravel.com and click the "Docs" button in the upper right corner, or use the Composer command "composershowlaravel/framework|grepversions". Staying updated can help improve project security and performance, but the impact on existing projects needs to be considered.

Staying Updated with Laravel: Benefits of Using the Latest VersionStaying Updated with Laravel: Benefits of Using the Latest VersionMay 13, 2025 am 12:08 AM

YoushouldupdatetothelatestLaravelversionforperformanceimprovements,enhancedsecurity,newfeatures,bettercommunitysupport,andlong-termmaintenance.1)Performance:Laravel9'sEloquentORMoptimizationsenhanceapplicationspeed.2)Security:Laravel8introducedbetter

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 Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor