溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Laravel8的路由與控制器實例分析

發布時間:2022-05-24 17:40:52 來源:億速云 閱讀:177 作者:zzz 欄目:編程語言

本篇內容介紹了“Laravel8的路由與控制器實例分析”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!

laravel訪問路徑是:
1 ) 路由—控制器—頁面/輸出
2 ) 路由—匿名函數—頁面/輸出

一、查看當前所有路由

進入當前項目的根目錄之后運行cmd
或者用IDE自帶的終端Terminal,快捷鍵 ALT+F12

 php artisan route:list

二、各種路由

在routes/web.php文件

我域名是www.la.com,按自己實際情況來

1.跳到視圖

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

視圖目錄位置:resources/views,存放的也是 HTML 內容。view()是一個助手函數,view(‘welcome’) 表示跳到welcome.blade.php視圖,也就是我們第一次啟動 Laravel 看到的那個歡迎頁面。

在瀏覽器地址欄寫:www.la.com/ 

2.直接輸出

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

3.帶參數的的路由

dump()是laravel的輔助函數,用來打印數據的

1)單個參數

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

瀏覽器運行http://www.la.com/show/1
結果:“1”
注意:是字符串

2)多個參數

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

瀏覽器運行:http://www.la.com/show/1/hello
結果:1,hello

4.路由參數添加限定 正則表達式

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

上述限定的意思是 age 參數只能接受數字,name 參數只能接受大小寫字母。

如果不滿足條件,結果:404 NOT FOUND

瀏覽器中運行:http://www.la.com/user/zhangsan/18
結果:zhangshan 18

5.路由組

1)第一種寫法Route::group(array(‘prefix’=>‘user’),function(){});

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

瀏覽器運行:

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

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

結果:

  • index

  • add

2)第二種寫法 Route::prefix(‘user’)->group(function(){});

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

6.跳到控制器

1)創建控制器,編寫方法

在項目根目錄運行

php artisan make:controller TestController
<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;class TestController extends Controller{
    public function hello(){
        echo "TestController的hello方法";
    }}

2)寫路由

在config/web.php最開始添加

use App\Http\Controllers\TestController;

然后寫路由

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

瀏覽器運行:http://www.la.com/hello

7.POST路由

laravel中為了防止csrf攻擊,我們在每一個post表單里面都要寫上一句 @csrf ,詳細可以點擊看我另一篇文章

  1. 我們先在views/user文件夾添加一個add.blade.php視圖

里面代碼:

<!DOCTYPE html><html><head>
    <title>測試POST提交</title></head><body>
    <form method="post" action="/user/insert">
        @csrf
        name:<input type="text" name="name">
        <input type="submit" value="提交" />
    </form></body></html>
  1. 添加路由

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路由驗證成功";
    });});

view('user.add')的意思是在resources/views目錄下的user文件夾下的add視圖 。(resources/views是默認路徑)
$request->all()獲取所有請求參數
dump() 打印數據

  1. 測試
    首先直接輸入http://www.la.com/user/insert肯定是不行的,會報錯(The GET method is not supported for this route. Supported methods: POST.)。
    Postman 輸入http://www.la.com/user/insert post提交失敗 返419 | Page Expired

所以我們先瀏覽器輸入http://www.la.com/user/add ,name隨便填啥點提交

8.Ajax路由

頭部要加入

通過js,傳遞 token,這里 name="_token" 隨便取什么名

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

<!DOCTYPE html><html><head>
    <meta charset="UTF-8">
    <title>CSRF</title>
    <meta name="_token" content="{{csrf_token()}}"></head><body><script src="/jquery-3.6.0.min.js"></script><script>
    $.ajax({
        url: "http://www.la.com/index",//本頁面
        type: "POST",
        data: {
            name:"名字"
        },
        headers: {
            'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
        },
        success: function (data) {
            console.log("200");
        }
    });</script></body></html>

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。

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

在瀏覽器中運行 www.la.com/user/profile

在瀏覽器中運行www.la.com/profile
結果:404 NOT FOUND

在瀏覽器中運行www.la.com/redirect

10.命名空間路由

之前寫的控制器 Controller 都直接寫在 Http\Controllers 文件夾之中,但實際情況是控制器也會分類,比如與管理員相關的操作會在 Controllers 中,再建一個文件夾 Admin,然 后把所有關于管理員的控制器類都放在這個文件夾中。如果這樣的話,就要添加名稱空間。

  1. 創建控制器
    方法一:使用phpartisan

php artisan make:controller Admin\IndexController

使用這種方法創建的控制器,自動加載名稱空間,如下圖所示
觀察與之前創建控制器php artisan make:controller TestController的區別

方法二:復制粘貼其他類
在Controllers文件夾下創建Admin文件夾,復制之前創建的控制器TestController,照著上圖修改。

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

  1. 控制器添加 index方法

public function index(){
       return "Admin文件夾下的IndexController中的index方法";}
  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']);//商品相關});

瀏覽器輸地址
http://www.la.com/admin
http://www.la.com/admin/user
http://www.la.com/admin/goods
結果都是一樣

“Laravel8的路由與控制器實例分析”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女