Table of Contents
1. View all current routes
2. Various routes
1. Jump to the view
2. Directly output
3. Route with parameters
1) Single parameter
2) Multiple parameters
4. Routing parameters added Restricted regular expression
5. Routing group
1) The first way to write Route::group(array('prefix'=>'user'),function(){});
2) The second way to write Route::prefix('user') ->group(function(){});
6. Jump to the controller
1) Create the controller and write the method
2) Write routing
7.POST routing
8.Ajax routing
9.带别名的路由
10.命名空间路由
Home PHP Framework Laravel Let's talk about Laravel8's routing and controller

Let's talk about Laravel8's routing and controller

May 24, 2022 am 11:55 AM
laravel

This article brings you relevant knowledge about laravel, which mainly introduces issues related to routing and controllers, including routing groups, jumps to controllers, post routing, and Ajax Routing and other related content, let’s take a look at it below, I hope it will be helpful to everyone.

Let's talk about Laravel8's routing and controller

[Related recommendations: laravel video tutorial]

laravel access path is:
1) Routing—Controller— Page/Output
2) Routing—Anonymous Function—Page/Output

1. View all current routes

Enter the root directory of the current project and run cmd
or use IDE to automate Terminal with the shortcut key ALT F12

 php artisan route:list
Copy after login

Lets talk about Laravel8s routing and controller

2. Various routes

In the routes/web.php file

My domain name is www.la.com, please choose according to your actual situation

1. Jump to the view

Route::get('/', function () {
    return view('welcome');});
Copy after login

View directory location: resources/views , which also stores HTML content. view() is a helper function. view(‘welcome’) means jumping to the welcome.blade.php view, which is the welcome page we see when we start Laravel for the first time.

Write: www.la.com/ in the browser address bar, the running result is:
Lets talk about Laravel8s routing and controller

2. Directly output

Route::get('ok', function () {
    echo "hello world";});
Copy after login

Lets talk about Laravel8s routing and controller

3. Route with parameters

dump() is laravel’s auxiliary function, used to print data

1) Single parameter

Route::get('show/{a}', function ($a) {
    dump($a);});
Copy after login

The browser runs http://www.la.com/show/1
Result: "1"
Note: It is a string

2) Multiple parameters

Route::get('show/{a}/{b}', function ($a,$b) {
   echo $a.','.$b;});
Copy after login

Browser running: http://www.la.com/show/1/hello
Result: 1,hello

4. Routing parameters added Restricted regular expression

Route::get('user/{name}/{age}', function ($name,$age) {
 echo $name.' '.$age; //直接输出 
 })->where('age','\d+')->where('name','[a-zA-Z]+');
Copy after login

The above restriction means that the age parameter can only accept numbers, and the name parameter can only accept uppercase and lowercase letters.

If the conditions are not met, the result is: 404 NOT FOUND

Run in browser: http://www.la.com/user/zhangsan/18
Result: zhangshan 18

5. Routing group

1) The first way to write Route::group(array('prefix'=>'user'),function(){});

Route::group(array('prefix'=>'user'),function(){
    Route::get('/index', function () {
        echo 'index';
    });
    Route::get('/add', function () {
        echo 'add';
    });});
Copy after login

Browser running:

  • http://www.la.com/user/index
  • http://www.la.com/user/add

Result:

  • index
  • add

2) The second way to write Route::prefix('user') ->group(function(){});

Route::prefix('user')->group(function(){
    Route::get('/index', function () {
        echo 'index';
    });
    Route::get('/add', function () {
        echo 'add';
    });});
Copy after login

6. Jump to the controller

1) Create the controller and write the method

to run in the project root directory

php artisan make:controller TestController
Copy after login

Lets talk about Laravel8s routing and controller

<?phpnamespace  App\Http\Controllers;use Illuminate\Http\Request;class TestController extends Controller{
    public function hello(){
        echo "TestController的hello方法";
    }}
Copy after login

2) Write routing

Add

use App\Http\Controllers\TestController;
Copy after login

at the beginning of config/web.php and then write routing

Route::get('/hello',[TestController::class,'hello']);//跳到控制器的方法
Copy after login

Browser running: http://www.la.com/hello
Result:
Lets talk about Laravel8s routing and controller

7.POST routing

in laravel In order to prevent csrf attacks, we must write the sentence @csrf in every post form. For details, you can click to read my other article

  1. We first enter views/user FolderAdd aadd.blade.phpView

Code inside:

nbsp;html>
    <title>测试POST提交</title>
    
Copy after login
        @csrf         name:              
  1. Add route
use Illuminate\Http\Request;Route::prefix('user')->group(function(){
    Route::get('/add', function () {
       return view('user.add');
    });
    Route::post('/insert', function (Request $request) {
        dump($request->all());
        echo "post路由验证成功";
    });});
Copy after login

view('user.add') means the add view under the user folder in the resources/views directory. (resources/views is the default path)
$request->all()Get all request parameters
dump() Print data
Lets talk about Laravel8s routing and controller

  1. Test
    First, entering http://www.la.com/user/insert directly will definitely not work and an error will be reported (The GET method is not supported for this route. Supported methods: POST .).
    Postman enters http://www.la.com/user/insert post submission fails and returns 419 | Page Expired
    Lets talk about Laravel8s routing and controller

So we first enter http:/ in the browser /www.la.com/user/add, fill in any name and submit
Lets talk about Laravel8s routing and controller

8.Ajax routing

The header should be added

Pass the token through js, here name="_token" you can choose any name

headers: {
‘X-CSRF-TOKEN’: $(‘meta[name="_token"]’).attr(‘content’)
},

nbsp;html>
    <meta>
    <title>CSRF</title>
    <meta><script></script><script>
    $.ajax({
        url: "http://www.la.com/index",//本页面
        type: "POST",
        data: {
            name:"名字"
        },
        headers: {
            &#39;X-CSRF-TOKEN&#39;: $(&#39;meta[name="_token"]&#39;).attr(&#39;content&#39;)
        },
        success: function (data) {
            console.log("200");
        }
    });</script>
Copy after login

9.带别名的路由

别名路由就是给某一个路由起一个别名,直接使用使用原名可以访问路由,但直接使用别名不能访问这个路由,同时在其他页面调用别名可以访问这个路由。

Route::get('user/profile',function(){ 
	return 'my url:'.route('profile');})->name('profile'); 	//创建一个路由 user/profile,这个路由的作用是返回路由 profile 的 RUL 地址,并给这个路由起一个别名 profile Route::get('redirect',function(){ 
	return redirect()->route('profile'); }); 	//创建一个名为 redirect 的路由,这个路由的作用是跳转到路由 profile。
Copy after login

route() 生成完整的URL
redirect()->route(‘profile’); //重定向命名路由

在浏览器中运行 www.la.com/user/profile
结果:Lets talk about Laravel8s routing and controller
在浏览器中运行www.la.com/profile
结果:404 NOT FOUND

在浏览器中运行www.la.com/redirect
结果:Lets talk about Laravel8s routing and controller

10.命名空间路由

之前写的控制器 Controller 都直接写在 Http\Controllers 文件夹之中,但实际情况是控制器也会分类,比如与管理员相关的操作会在 Controllers 中,再建一个文件夹 Admin,然 后把所有关于管理员的控制器类都放在这个文件夹中。如果这样的话,就要添加名称空间。

  1. 创建控制器
    方法一:使用phpartisan
php artisan make:controller Admin\IndexController
Copy after login

使用这种方法创建的控制器,自动加载名称空间,如下图所示
观察与之前创建控制器php artisan make:controller TestController的区别
Lets talk about Laravel8s routing and controller
方法二:复制粘贴其他类
在Controllers文件夹下创建Admin文件夹,复制之前创建的控制器TestController,照着上图修改。

命名空间 namespace App\Http\Controllers\Admin;
添加类引用 use App\Http\Controllers\Controller;

  1. 控制器添加 index方法
public function index(){
       return "Admin文件夹下的IndexController中的index方法";}
Copy after login
  1. 写路由
    web.php文件
use App\Http\Controllers\Admin\IndexController;Route::group(['namespace'=>'Admin'],function(){
    Route::get('admin',[IndexController::class,'index']);//管理员的主页
    Route::get('admin/user',[IndexController::class,'index']);//管理员用户相关
    Route::get('admin/goods',[IndexController::class,'index']);//商品相关});
Copy after login

浏览器输地址
http://www.la.com/admin
http://www.la.com/admin/user
http://www.la.com/admin/goods
结果都是一样

【相关推荐:laravel视频教程

The above is the detailed content of Let's talk about Laravel8's routing and controller. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

How to learn Laravel How to learn Laravel for free How to learn Laravel How to learn Laravel for free Apr 18, 2025 pm 12:51 PM

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

What versions of laravel are there? How to choose the version of laravel for beginners What versions of laravel are there? How to choose the version of laravel for beginners Apr 18, 2025 pm 01:03 PM

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

How to view the version number of laravel? How to view the version number of laravel How to view the version number of laravel? How to view the version number of laravel Apr 18, 2025 pm 01:00 PM

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

Laravel user login function Laravel user login function Apr 18, 2025 pm 12:48 PM

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

The difference between laravel and thinkphp The difference between laravel and thinkphp Apr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

See all articles