Home > PHP Framework > Laravel > Let's talk about Laravel8's routing and controller

Let's talk about Laravel8's routing and controller

WBOY
Release: 2022-05-24 11:55:08
forward
2723 people have browsed it

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!

Related labels:
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template