laravel中的动态网址

时间:2014-10-16 11:39:51

标签: php url dynamic laravel url-routing

我是laravel的初学者所以请原谅我这是一个简单的问题

我正在尝试通过我的url传递db变量,例如blog?= category 它会显示所有结果,但是当我将网址更改为博客/类别1时,它不会显示任何内容。

数据库字段:id,category,name           1类1测试

这是我的路线:

Route::get( '/blog', 'BlogController@index' );
Route::get('/', 'HomeController@index');
 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

由于

1 个答案:

答案 0 :(得分: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);
});