在 laravel 中,路由在 paths/ 文件夹中定义。路由在 web.php 文件中定义。该文件是在 laravel 安装完成后创建的。 laravel 路由接受 uri 和闭包函数,如下所示 -
use illuminate\support\facades\route;route::get('/student', function () { return 'hello student';});
在web/routes.php中定义的路由被分配到web中间件组中,并且它们具有会话状态和csrf保护。您还可以在路由中调用控制器如下所示 -
use illuminate\support\facades\route;use app\http\controllers\studentcontroller;route::get('student', [studentcontroller::class, 'index']);
以下是您可以在应用程序中使用的路由方法:
route::get($ uri, $回调函数或控制器);
route::post($uri, $回调函数或控制器);
route::put($uri, $回调函数或控制器);
route::patch($uri, $回调函数或控制器);
route::delete($uri, $回调函数或控制器);
route::options($uri, $回调函数或控制器);
路由参数验证路线参数位于大括号内,并且给出的名称包含字母数字字符。除了字母数字之外,您在选择路由参数名称时还可以使用下划线。
语法路由参数的语法如下所示−
route::get('/user/{myid}', function ($myid) { //});
这里myid是我们要进一步使用的路由参数。
多个路由参数您可以像下面的语法所示,拥有多个路由参数。
route::get('/students/{post}/feedbacks/{feedback}', function ($postid, $feedbackid) { //});
在上述情况下,有两个路由参数:{post}和{feedback}
可选参数您还可以为路由添加可选参数。可选参数并不总是可用,参数后面用?表示。可选参数的语法如下所示 −
route::get('/students/{myname?}', function ($myname = null) { return $myname;});
这里 myname 是一个可选参数。
laravel有一些方法可以帮助验证参数。它们是where(),wherenumber(),wherealpha()和wherealphanumeric()。
example 1 的中文翻译为:示例1使用where()方法
where()方法在路由上定义,它将接受参数名称和应用于参数的验证。如果有多个参数,它将以数组形式接受,其中键为参数名称,值为要应用于键的验证规则。
route::get('/student/{studentname}', function ($studentname) { return $studentname;})->where('studentname', '[a-za-z]+');
输出输出为 −
disha
在上述情况下,学生姓名必须包含 a-z 或 a-z 或两者的混合。因此以下是有效的网址 -
http://localhost:8000/student/dishahttp://localhost:8000/student/dishasingh.
无效网址 -
http://localhost:8000/student/dishasingh123
示例 2现在让我们使用 where() 方法检查多个参数。
route::get('/student/{studentid}/{studentname}', function ($studentid, $studentname){ return $studentid.===.$studentname;})->where(['studentid' => '[0-9]+', 'studentname' => '[a-z]+']);
在上述情况中,路由参数是studentid和studentname。studentid必须是 0-9 之间的数字,学生姓名必须小写。
需要翻译的内容为:必须是0-9之间的数字,并且studentname必须为小写输出上述的输出为−
12===disha
上述的有效网址为−
http://localhost:8000/student/12/dishahttp://localhost:8000/student/01/disha
无效网址 -
http://localhost:8000/student/01/dishahttp://localhost:8000/student/abcd/disha
使用 wherenumber()示例您需要传递您希望仅为有效值的路由参数 -
route::get('/student/{studentid}/{studentname}', function ($studentid, $studentname) { return $studentid.===.$studentname;})->wherenumber('studentid')->where('studentname','[a-z]+');
输出上述代码的输出为 −
12===disha
使用 wherealpha() 示例您需要传递您希望具有 alpha 值的路由参数 -
route::get('/student/{studentid}/{studentname}', function ($studentid, $studentname) { return $studentid.===.$studentname;})->wherenumber('studentid')->wherealpha('studentname');
输出上述代码的输出为 −
12===dishasingh
使用 wherealphanumeric()示例您需要传递您希望具有字母数字值的路由参数−
route::get('/student/{studentid}/{studentname}', function ($studentid, $studentname) { return $studentid.===.$studentname;})->wherenumber('studentid')->wherealphanumeric ('studentname');
输出输出将是 -
12===dishasingh122
以上就是如何在laravel中验证路由参数?的详细内容。