2014-10-16 30 views
0

我laravel是初學者所以請原諒我,如果這是一個簡單的問題Dyanmic網址

我想通過我的URL來傳遞一個數據庫變量,因此如博客?= 類別它顯示了所有的結果,但當我將網址更改爲blog/category1時,它不顯示任何內容。

數據庫字段:ID,類別,名稱 1個組別測試

這是我的路線:

Route::get('/blog', '[email protected]'); 
Route::get('/', '[email protected]'); 
Route::get('blog/{category}', function($category = null) 
{ 
// get all the blog stuff from database 
// if a category was passed, use that 
// if no category, get all posts 
if ($category) 
$posts = Post::where('category', '=', $category); 
else 
$posts = Post::all(); 

// show the view with blog posts (app/views/blog.blade.php) 
return View::make('blog.index') 
->with('posts', $posts); 
}); 

BlogController

class BlogController extends BaseController { 


    public function index() 
    { 
     // get the posts from the database by asking the Active Record for "all" 
     $posts = Post::all(); 

     // and create a view which we return - note dot syntax to go into folder 
     return View::make('blog.index', array('posts' => $posts)); 
    } 
} 

這是我的看法佈局:

@extends('base') 

@section('content') 
@foreach ($posts as $post) 
<h2>{{ $post->id }}</h2> 
<p>{{ $post->name }}</p> 
@endforeach 
@stop 

謝謝

回答

2

您需要在Eloquent查詢後添加->get()以獲取結果。

Route::get('blog/{category}', function($category = null) 
{ 
    // get all the blog stuff from database 
    // if a category was passed, use that 
    // if no category, get all posts 
    if ($category) 
     $posts = Post::where('category', '=', $category)->get(); 
    else 
     $posts = Post::all(); 

    // show the view with blog posts (app/views/blog.blade.php) 
    return View::make('blog.index')->with('posts', $posts); 
}); 
+0

傳說!現在工作 – 2014-10-16 11:59:11

+0

很高興我能幫忙。考慮將此答案標記爲解決方案。 ;) – Jerodev 2014-10-16 12:59:34

+0

+1我沒有注意到缺少' - > get()' – 2014-10-16 13:20:42