4、PHP之路由

一、基础路由

//闭包路由
Route::get('/',funtion(){
    return 'beautiful';
})

Route::post('/',funtion(){
    return 'beautiful';
})

Route::any('/',funtion(){
    return 'beautiful';
})

Route::match(['get','post'],'/',funtion(){
    return 'beautiful';
})

二、重定向路由(默认返回302)

Route::redirect('/here', '/there');

//自定义返回状态码
Route::redirect('/here', '/there', 301);

//使用permanentRedirect方法来返回301
Route::permanentRedirect('/here', '/there');

三、视图路由

//view方法: 第一个是必填参数,是包含视图名称的 URI 。第二个也是必填参数,是需要渲染的视图名称。此外,还可以通过数组传递一组数据给视图,作为可选的第三个参数:
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);

四、路由参数

//必填参数(一个参数)
Route::get('user/{id}', function ($id) {
    return 'User '.$id;
});

//必填参数(多个参数)
Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
    //
});

//可选参数
Route::get('user/{name?}', function ($name = null) {
    return $name;
});

//正则表达式约束
Route::get('user/{id}/{name}', function ($id, $name) {
    //
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

//全局约束(应用到所有使用id参数的路由上)
public function boot()
{
    Route::pattern('id', '[0-9]+');

    parent::boot();
}

//编码正斜杠字符(Laravel 路由组件允许除 / 之外的所有字符。你必须使用 where 条件正则表达式显式地允许 / 成为占位符的一部分)
Route::get('search/{search}', function ($search) {
    return $search;
})->where('search', '.*');

//路由命名(name方法可以指定路由名称)
Route::get('user/profile', function () {
    //
})->name('profile');

//指定控制器行为的路由名称
Route::get('user/profile', 'UserProfileController@show')->name('profile');

五、中间件(创建中间件:php artisan make:middleware CheckAge,该命令会在app/Http/Middleware 目录下)

Route::middleware(['first', 'second'])->group(function () {
    Route::get('/', function () {
        // 使用 first 和 second 中间件
    });

    Route::get('user/profile', function () {
        // 使用 first 和 second 中间件
    });
});

六、命名空间

Route::namespace('Admin')->group(function () {
    // 在 「App\Http\Controllers\Admin」 命名空间下的控制器
});
//注:默认情况下,RouteServiceProvider 会在命名空间组中引入你的路由文件,让你不用指定完整的 App\Http\Controllers 命名空间前缀就能注册控制器路由。

七、路由前缀

Route::prefix('admin')->group(function () {
    Route::get('users', function () {
        // 匹配包含 「/admin/users」 的 URL
    });
});

八、路由名称前缀

Route::name('admin.')->group(function () {
    Route::get('users', function () {
        // 指定路由名为 「admin.users」...
    })->name('users');
});

九、控制器(生成控制器:php artisan make:controller ShowProfile,该命令会在App\Http\Controllers目录下)

Route::get('user/{id}', 'UserController@show');

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值