Laravel5.6入门(二)

Lkeme SVIP+

前言

laravel5.6学习记录,学习最新的版本.

Laravel5.6

路由

Route就是根据Url分配不同的处理程序.

我们可以使用

1
php artisan route:list

查看程序默认的路由信息.

首页/路由的处理是一个Closure闭包函数.

1
2
3
4
//route/web.php
Route::get('/', function () {
return view('welcome');
});

get()是请求方式,/代表首页,welcome是视图文件,
view('视图目录.视图文件名') 目录以.连接,视图文件名不需要.blade.php后缀
函数可以直接定位到视图目录 Resources/views/*中.

请求方式有:

1
2
3
4
5
6
Route::get($uri, $callback); //取
Route::post($uri, $callback); //新建
Route::put($uri, $callback); //更新完整
Route::patch($uri, $callback); //更新部分
Route::delete($uri, $callback); //删除
Route::options($uri, $callback);

我们可以新建一个路由和视图测试.

get请求/study,返回views/study/index.blade.php视图

访问http://laravel.study/study

我们可以再次查看一下路由信息

这样就完成了一个非常简单的路由,把视图和路由关联在一起了

路由和控制器绑定

因为还没讲到控制器,所以就代码示例,把闭包函数部分替换成控制器@方法即可

1
2
Route::get('user/profile', 'UserController@index');
//UserController 控制器名 @ index 函数

常用请求方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Route::get('foo', function () {
// 基本方式
//TODO
});
Route::post('foo', function () {
// 基本方式
//TODO
});
Route::match(['get', 'post'], '/', function () {
// 基本方式,匹配get和post
//TODO
});
Route::any('foo', function () {
// 基本方式,所有请求方式
//TODO
});

路由参数

  • 必填参数
  • 可选参数
    1
    2
    3
    4
    Route::get('user/{name?}', function ($name = 'John') {
    return $name;
    });
    //可选参数使用?号标记,但是一定要有个默认值

路由正则

正则匹配可以使用链式操作->where('参数名','正则')

1
2
3
4
Route::get('user/{name}', function ($name) {
//
})->where('name', '[A-Za-z]+');

路由命名

路由命名也可以使用链式操作->name('别名'),或者使用Route::name('别名')

1
2
3
4
5
6
7
8
9
Route::get('user/profile', function () {
//
})->name('profile');
Route::get('user/profile', 'UserController@showProfile')->name('profile');

//第二种
Route::name('profile')->get('user/profile', function () {
//
});

路由命名主要使用在 route('路由名')函数

1
2
3
4
// 生成 URL...
$url = route('profile');
// 生成重定向...
return redirect()->route('profile');

路由这块姿势很多,更复杂的用到的时候再说

End.

  • 标题: Laravel5.6入门(二)
  • 作者: Lkeme
  • 创建于 : 2018-02-22 16:11:51
  • 更新于 : 2024-04-15 15:30:53
  • 链接: https://mudew.com/2018/02/22/Laravel5-6入门-二/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论