我需要验证我博客的url。我只需要允许主要的URL站点,例如:
https://www.example.com/2019/02/11/post_title/
如何在Laravel中路由它?
我想做这样的事情:
Route::get('{slug}', function(){
$post = \App\Post::where('slug', $slug)->firstOrFail();
});
答案 0 :(得分:0)
这是您的起点
Route::get('/{year}/{month}/{day}/{title}', function ($year, $month, $day, $title) {
$date = DateTime::createFromFormat('Y/m/d', $year . '/' . $month . '/' . $day);
$date_errors = DateTime::getLastErrors();
if ($date_errors['warning_count'] || $date_errors['error_count']) {
dd('invalid date');
}
// do stuff
dd($year, $month, $day, $date_errors, $date);
})->where(['year' => '^(19|20)\d{2}$', 'month' => '^(0?[1-9]|1[012])$', 'day' => '^[0-9]*$']);
如果年份与Reg表达式不匹配(从1900到2099)并且在1到12个月内,则将出现404错误
答案 1 :(得分:0)
我想要:(原谅我不好的正则表达式)
Route::get('/{date}/{title}', 'Controller@method')
->where('date', '[a-Z]+\/+[a-Z]+\/+[a-Z]')
然后在Controller中:
method ($date, $title) {
$date = Carbon\Carbon::parseFromFormat('Y/m/d', $date);
...