laravel框架---基本路由

英文文档-路由
中文文档-路由

1、路由的使用
    a、第一个参数跟url有关
        比如:
        Route::get('student/index', 'StudentController@index');
        本地访问此路由就是:http://localhost/laravel/public/student/index
    b、第二个参数通常是路由器访问的控制器(@+:表示访问的控制器的方法)
2、路由有好多钟:
    Route::get($uri, $callback);
    Route::post($uri, $callback);
    Route::put($uri, $callback);
    Route::patch($uri, $callback);
    Route::delete($uri, $callback);
    Route::options($uri, $callback);
    //上面这几种用法一样

    Route::match(['get', 'post'], '/', function () {
        //
    });
    //此方法表示可以接收多请求如get或post
    Route::any('foo', function () {
        //
    });
    //此方法可以接收上面任意一个的请求如get、post、put...
3、路由的使用
    传参
    Route::get('/', function () {
        return view('welcome', ['website' => 'zwh']);
    });

    获取url请求参数id
    Route::get('user/{id}', function ($id) {
        return 'User '.$id;
    });
    获取url上多个请求参数
    Route::get('posts/{post}/comments/{comment}', function ($post, $comment) {
       return 'post-'.$post.' comment-'.$comment;
    });

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

    使用where正则表达式约束参数
    Route::get('user/{name?}', function ($name = 'John') {
        return $name;
    })->where('name', '[A-Za-z]+');

    命名路由
    生成 URL 或重定向提供了方便
    Route::get('user/nameis', function () {
        return 'my url: ' . route('profile');
    })->name('profile');;
    Route::get('redirect', function () {
        return redirect()->route('profile');
    });
    如果命名路由定义了参数,可以将该参数作为第二个参数传递给 route 函数。给定的路由参数将会自动插入到 URL中
    Route::get('user/{id}/profile', function ($id) {
        //$url = route('profile', ['id' => 1]);
        $url = route('profile', $id);
        return $url;
    })->name('profile');

    路由组
    为每个路由的url添加上admin
    Route::prefix('admin')->group(function () {
        Route::get('users', function () {
            return route('zzz');
        })->name('zzz');
    });

    注入模型model到路由
    Route::get('users/{user}', function (App\Student $user) {
        dd($user);
    });

猜你喜欢

转载自blog.csdn.net/ZWHSOUL/article/details/80378207