我有两个从数据库$month和$id中提取的变量。当我执行$if(isset($slug))if时,查询数据库并显示结果。当我对$month做同样的操作时,它不会输出任何内容,但会加载页面。我看不出代码有什么问题,因为它都匹配??
routes.php
Route::get('blog/{id}', ['as' => 'blog.id', 'uses' => 'BlogController@ShowbyId']);
Route::get('blog/{month}', ['as' => 'blog.month', 'uses' => 'BlogController@ShowbyMonth']);
<?php class BlogController extends BaseController {
public function ShowAll() {
$blogs = Blog::all();
$blogs = DB::table('blogs')->paginate(3);
return View::make('pages.blog')
->with('blogs', $blogs);
}
public function ShowById($id) {
$ids = Blog::where('id', $id)
->get();
return View::make('pages.blog')
->with('ids', $ids);
}
public function ShowByMonth($month) {
$months = Blog::where('month', $month);
$months = DB::table('blogs')->paginate(3);
return View::make('pages.blog')
->with('months', $months);
}
}
blog.blade.php
@if(isset($blogs))
@foreach ($blogs as $blog)
<div class="blog-outer-wrap">
<img src="images/blog/{{ $blog->img}}">
<div class="blog-header">{{ $blog->header }}</div>
<div class="blog-text">{{ $blog->content }}</div>
<a href="{{ URL::route('blog.id', [$blog->id]) }}"><div class="blog-readmore">Read More</div>
</div>
@endforeach
@elseif(isset($ids))
@foreach ($ids as $id)
<div class="blog-outer-wrap">
<img src="../images/blog/{{ $id->img}}">
<div class="blog-header">{{ $id->header }}</div>
<div class="blog-text">{{ $id->content }}</div>
</div>
@endforeach
@elseif(isset($months))
@foreach ($months as $month)
<div class="blog-outer-wrap">
<img src="images/blog/{{ $month->img}}">
<div class="blog-header">{{ $month->header }}</div>
<div class="blog-text">{{ $month->content }}</div>
<a href="{{ URL::route('blog.month', [$month->slug]) }}"><div class="blog-readmore">Read
</div>
@endforeach
@endif
由于我不能发表评论,我将作为答案发布。
您的两条路线:
Route::get('blog/{id}', . . . );
Route::get('blog/{month}', . . . );
是一样的,任何uri blog/whatever
无论如何都会命中第一个路由,第二个永远不会被命中,因为第一个通配符{id}将接受任何参数。所以你总是点击BlogController@ShowById
所以我猜你会在一个月内通过ShowByMonth控制器。相反,它会将您路由到:
public function ShowById($id) {
$ids = Blog::where('id', $id)
->get();
return View::make('pages.blog')
->with('ids', $ids);
}
您的查询变成Blog::where('id', 'January');
的位置,或者您放入uri的任何月份。
修复:
添加限制
Route::get('blog/{id}', [
'as' => 'blog.id',
'uses' => 'BlogController@ShowbyId']
)->where('id', '[0-9]+'); // Only if {id} is any integer
Route::get('blog/{month}', [
'as' => 'blog.month',
'uses' => 'BlogController@ShowbyMonth']
)->where('month', '[A-Za-z]+'); // Only if {month} is any alpha character