Laravel数据库内容未显示

时间:2014-10-19 20:36:59

标签: php if-statement laravel routes

我从DB $ month和$ id中提取了2个变量。当我执行$ if(isset($ slug))时查询数据库并显示结果。当我为$ 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

1 个答案:

答案 0 :(得分:2)

由于我无法发表评论,我将发布作为答案。

你的两条路线:

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