路由其实就是从源地址传送到目的地,下面对mvc+route进行图形详解
基础路由:
Route::get('/get',function(){
return 'get';
});
Route::post('/post',function(){
returnho 'post';
});
Route::put('/put',function(){
return 'put';
});
Route::delete('/delete',function(){
returno 'delete';
});
Route::patch('/patch',function(){
returno 'patch';
});
Route::options('/delete',function(){
return 'delete';
});
// 匹配[]里面的路由信息
Route::match(['get', 'post','put'], '/getPost', function () {
return 'Hello World';
});
//匹配任何一个
Route::any('foo', function () {
return 'Hello World1';
});
必选参数路由:参数是必填项,
Route::get('/updateinfo/{id}',function($id){
echo '这是用户后台'.$id;
});
Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
echo '这是用户后台'.$postId. ':'.$commentId;
});
可选参数路由
Route::get('user/{name?}', function ($name = null) {
return $name;
});
Route::get('user/{name?}', function ($name = 'John') {
return $name;
});
例如:
Route::get('posts/{post}/comments/{comment?}', function ($postId, $commentId =null) {
echo '这是用户后台'.$postId. ':'.$commentId;
});
路由参数进行类型限制(采用正则方式)
Route::get('user/{name}', function ($name) {
//后面跟where进行正则的校验
})
->where('name', '[A-Za-z]+');
设置全局路由限制
/**
* 定义你的路由模型绑定,模式过滤器等。
*
* @param \Illuminate\Routing\Router $router
* @return void
*/public function boot(Router $router){
$router->pattern('id', '[0-9]+');
parent::boot($router);}
在此调用路由时,就不需要在填写where设置
注意:在多个参数时,一般最后一个参数可以选择可选的,如果第一个参数或者中的某些参数设置为可选参数则报错误信息
使用路由:
路由请求方式主要分为:post、get、put、delete、patch、options等。
在使用put时序Route::put('/edit',function(){}时,需在表单添加隐藏域来确认这是一条
put数据,否则会提示错误,同理在delete也是
<input type="hidden" name="_method" value="PUT" size="50" /><br>
<input type="hidden" name="_method" value="DELETE" size="50" /><br>
路由错误提示:
1、路由错误提示:MethodNotAllowedHttpExceptionin RouteCollection.php line 219:
意思:当前的请求方式和路由的规则请求方式不匹配
2、InvalidArgumentExceptionin FileViewFinder.php line 137:View [from] not found.
意思:没有发现from视图模板文件,注意:在laravel中模板文件存在resources/中,
以from.blade.php中 blade必须存在遵循laravel框架命名规则
3、TokenMismatchException in VerfyCsrfToken.phpline 53.
意思:当前post请求中缺少验证信息 注意:需要在from表单中添加token隐藏域 {{csrf_field()}}防止csrf攻击
***刚才也说了,路由只是一个桥梁,如何使用路由把视图层和控制层连接起来呢?
答:官网手册里设这样写的View层代码:
<form method="POST" action="/password/email">
{!! csrf_field() !!}
@if (count($errors) > 0)
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
@endif
<div>
Email <input type="email" name="email" value="{{ old('email') }}">
</div>
<div>
<button type="submit">
发送重置密码邮件 </button>
</div></form>
路由代码:
Route::post('password/email', 'Auth\PasswordController@postEmail');
Auth:进行权限验证操作通过后传到
PasswordController控制器中
在laravel中mvc+路由之间的关系图解: