Laravel 簡單入門,路由的使用(一)


一、安裝 Laravel

Laravel 使用 Composer 來管理項目依賴。因此,在使用 Laravel 之前,請確保您的機器上已經安裝了 Composer。

composer create-project --prefer-dist laravel/laravel blog

 

 

 

二、路由的定義

1、路由的定義文件在根目錄 routes/web.php 中,可以采用了:

(1)::get()這個方法,它接受的就是 GET 提交
(2)::post()、::put()、::delete()是表單和 Ajax 的提交接受方式
(3)::any()表示不管你是哪種提交方式,我智能的全部接收響應
(4)::match()表示接收你指定的提交方式,用數組作為參數傳遞
//只能接受get請求
Route::get("index",function (){
    return "Hello,Laravel!";
});
//只能接受get請求
Route::post("index",function (){
    return "Hello,Laravel!";
});
//全部接收響應
Route::any("index",function (){
    return "Hello,Laravel!";
});
//match()表示接收你指定的提交方式
Route::match(['get','post'],'index',function (){
    return "Hello,Laravel!";
});
//http://la8.com/index

2、路由參數可分為必填參數和可選參數

//必填參數,http://la8.com/user/1
Route::get('user/{id}', function ($id) {
    return 'User '.$id;
});
//多個參數,http://la8.com/posts/1/comments/2
Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
    return 'posts:'.$postId.',comments:'.$commentId;
});

//可選參數
Route::get('user/{name?}', function ($name = null) {
    return $name;
});

 3、正則表達式約束

你可以使用路由實例上的 where 方法約束路由參數的格式。where 方法接受參數名稱和定義參數應如何約束的正則表達式:

Route::get('user/{id}/{name}', function ($id, $name) {
    return 'User '.$id.',name:'.$name;
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);
如果想讓約束 id 只能是 0-9 之間作用域全局范圍,可以在模型綁定器里設置; 模型綁定器路徑為:app\Providers\RouteServiceProvider 的 boot()方法;
public function boot()
{
    //
    Route::pattern('id', '[0-9]+');
    parent::boot();
}
注:如果 id 已經被全局約束,在某個局部你想讓它脫離約束,可以如下操作:...->where('id', '.*')

4.路由重定向

可以設置訪問一個路由的 URI,跳轉到另一個路由的 URI,在web.php具體如下:
Route::redirect('index', 'task');

5、路由命名

路由命名可以方便地為指定路由生成 URL 或者重定向。通過在路由定義上鏈式調用 name 方法可以指定路由名稱

//通過設置路由來訪問創建好的控制器,參數二:控制器@方法名
Route::get("task/url","TaskController@url")->name('task.url');
//http://la8.com/task/url

注意:路由命名必須是唯一的

6、路由分組和前綴

路由分組功能是為了讓大量路由共享路由屬性,包括中間件、命名空間等;
//route分組
Route::group(['prefix'=>'api'],function (){
    Route::get("test2",function (){
        return "index";
    });
});

//route分組,推薦使用
Route::prefix('api')->group(function (){
    Route::get("test2",function (){
        return "index";
    });
});

prefix 方法將會為路由組中的每一個 URI 添加前綴。例如,您可以給該組中所有的 URI 添加 admin 的前綴:

Route::prefix('admin')->group(function () {
    Route::get('users', function () {
        return "users";
    });
});
//http://la8.com/admin/users

Route::prefix('admin')->group(function () {
    Route::get('data1', 'DataController@index');
    Route::get('data2', 'DataController@index2');
});
//http://la8.com/admin/data1
//http://la8.com/admin/data2
7、命名空間,控制器嵌套

 在\app\Http\Controllers\Admin\ManageController.php控制器:

//控制器嵌套,命名空間的設置
Route::namespace('Admin')->group(function (){
    Route::get("manage","ManageController@index");
});
//http://la8.com/manage

8、路由名稱前綴

//方式一
Route::group(['as'=>'lhs.'], function () {
    Route::get('roc', function () {
        //route() 函數為指定的路由生成路由 URL。
        return route('lhs.index');//輸出:http://la8.com/roc
    })->name('index');
});

//方式二
Route::name('lhs.')->group(function () {
    Route::get('roc', function () {
        //route() 函數為指定的路由生成路由 URL。
        return route('lhs.users');//輸出:http://la8.com/roc
    })->name('users');
});

9、路由回退

如果我們跳轉到了一個不存在路由時,會產生 404 錯誤,體驗不佳;可以使用回退路由,讓不存在的路由自動跳轉到你指定的頁面去;
Route::fallback(function (){
   return redirect("/");
});

注:回退路由,注意要放在最底部

10、路由重定向

(1). 重定向使用助手函數 redirect()的 to()方法,注意需要 return 才能跳轉;
return redirect()->to('/'); //跳到首頁 
return redirect()->to('task'); //跳轉到 task 
return redirect()->to('task/url'); //跳轉到 task/url
(2). 也可以直接使用快捷方式直接進行跳轉;
return redirect('/'); //跳到首頁 return 
redirect('task'); //跳轉到 task return 
redirect('task/url'); //跳轉到 task/url
(3). redirect()助手有一個對應的 facade 模式對象;
return Redirect::to('/'); //facade 模式,但需要 use 引入
(4). 使用 redirect()的 route()方法,可以跳轉到指定的命名路由 URI; 
return redirect()->route('task.index'); //注意和 route()方法區別
(5). 使用 redirect()的 back()方法,可以重定向到上一個頁面中;
return redirect()->back();
return back(); //快捷方式
(6). 使用 redirect()的 action()方法,可以直接重定向到控制器方法;
return redirect()->action('TaskController@index'); //需注冊路由 
return redirect()->action('TaskController@index', ['id'=>10]);
(7). 使用 redirect()的 away()方法,跳轉到外部鏈接;
return redirect()->away('http://www.baidu.com'); //不帶任何編碼

 11、表單偽造和 CSRF 保護

HTML表單支持GET請求,但表單不支持 PUT, PATCH 或 DELETE 請求

Route::get('task/form', 'TaskController@form');
Route::any('task/getform', function () {
    return \Illuminate\Support\Facades\Request::method();
});
<form action="/task/getform" method="post">
    <button type="submit">提交</button>
</form>
表單頁以 post 發送,路由也使用 post 接受,以下表單提交會出現 419 錯誤;
這是為了避免被跨站請求偽造攻擊,框架提供了 CSRF 令牌保護,請求時驗證;
<input type="hidden" name="_token" value="{{csrf_token()}}">

HTML 表單調用請求方式為 PUT, PATCH 或 DELET 的路由時,您需要在表單中添加一個 _method 的隱藏域。_method 的值將會作為 HTTP 請求的方法:

<form action="/task/getform" method="post">
    <input type="hidden" name="_method" value="PUT">
    <input type="hidden" name="_token" value="{{csrf_token()}}">
    <button type="submit">提交</button>
</form>
對於 CSRF 令牌保護和表單偽造提交方式,也支持快捷方式的聲明,如下:
@csrf 
@method('PUT')

 

 

 

laravel官網:https://learnku.com/docs/laravel/8.x/installation/9354


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM