初学Laravel框架,自定义路由整了半天...各种搜资料算是搞定了,把自己的经验分享一下~
首先,这个路由是个什么玩意?
路由就是当访问特定路径时,使用特定的方法来处理这个请求并且显示出相应的页面。比如,你想实现在访问/welcome路径时显示“Welcome to my world~”,那你就定义一个路由,对应路径是/welcome,然后指定一个用于显示“Welcome to my world~”方法对这个路径的访问请求进行处理。
然后,我们要怎么实现自定义路由呢?
首先,在/app/Http/Controller目录下,建立自己的控制器文件,自定义方法,为避免冲突,请同时定义namespace,这是我的控制器文件AdminController.php:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class AdminController { public function getIndex(Request $request) { echo 'plz post param'; } public function postIndex(Request $request) { echo 'succeed!'; $data = $request->input('param'); $res = unserialize($data); } }
然后,在routes/web.php中,定义路由,格式是Route::<method>(<路径>,<控制器文件名>@<方法名>)
这里的method,是指定请求方式的,如get,post等。如果不限定方式,这里可以写any
<?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Route::get('/admin','[email protected]'); Route::post('/admin','[email protected]');
还有一步,因为laravel框架自带CSRF防跨站攻击机制,所以如果你只是这么写可能会在访问路由的时候出现419 Page expire错误,因为token参数不对,只需要在/app/Http/MiddleWare/VerifyCsrfToken.php中排除你的自定义路由路径即可
<?php namespace App\Http\Middleware; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware; class VerifyCsrfToken extends Middleware { /** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = [ "/admin" //排除路径 ]; }
然后就可以访问你的自定义路由了~
注意,有时候直接用127.0.0.1/admin是不行的,不知道为什么好像windows上会出这个问题,解决方法是访问127.0.0.1/index.php/admin就行了,我也不知道为什么
文章评论