我希望能够显示不同的内容,具体取决于在url中调用的变量。想知道$ slug是slug,让我们说它是一个帖子ID,所以如果$ id是活动的,那么只显示其他帖子如果$ month处于活动状态,则显示该月的所有帖子elseif $ month和$ id = null显示全部。这就是我想要实现的目标
routes.php文件
Route::get('blog/{slug}', ['as' => 'blog.slug', 'uses' => 'BlogController@getSlug']);
Route::get('blog/{month}', ['as' => 'blog.slug', 'uses' => 'BlogController@getSlug']);
BlogController.php
<?php
类BlogController扩展了BaseController {
public function BlogIndex()
{
//get the posts from the database by asking the Active Record for "all"
$blogs = Blog::all();
$blogs = DB::table('blogs')->paginate(3);
// and create a view which we return - note dot syntax to go into folder
return View::make('pages.blog', array('blogs' => $blogs));
}
public function ShowbySlug($slug)
{
$blogs = Blog::where('slug', '=', $slug)->get();
// show the view with blog posts (app/views/pages/blog.blade.php)
return View::make('pages.blog')
->with('slug', $slug)
->with('blogs', $blogs);
}
public function ShowbyMonth($month)
{
$blogs = Blog::where('month', '=', $month)->get();
// show the view with blog posts (app/views/pages/blog.blade.php)
return View::make('pages.blog')
->with('month', $month)
->with('blogs', $blogs);
}
}
blog.blade.php
@foreach ($blogs as $blog)
@if(isset($blogs))
<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.slug', [$blog->slug]) }}">
</div>
@elseif(isset($slug))
<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>
</div>
@endif
@endforeach
答案 0 :(得分:1)
你真的不能这样做,因为你刚刚宣布了两次相同的路线。当您说路线为blog/{slug}
时,slug
只是一个占位符。它与blog/{month}
完全相同。它只是说:“我希望blog/
后跟任何。”如果您拨打任何内容 slug
或month
,则无关紧要。也就是说,参数不会相加。
你可以做的是,如果你认为slug
总是一个字符串而month
总是一个数字(或月份的名称²),那么就应用于{{3像这样:
// Route for all blog posts
Route::get('blog', 'BlogController@showAll');
// Route for all blog posts in a month; only numbers as parameters
Route::get('blog/{month}', 'BlogController@showByMonth')
->where('month', '[0-9]+');
// Route for all blog posts by title; anything else as parameters
Route::get('blog/{slang}', 'BlogController@showBySlang');
在您的控制器上,定义三种方法,每种方法一种:
public function showAll() {
$blogs = Blog::all();
return View::make('pages.blog')
->with('blogs', $blogs);
}
public function showByMonth($month) {
$blogs = Blog::where('month', $month)
->get();
return View::make('pages.blog')
->with('blogs', $blogs);
}
public function showBySlug($slug) {
$blogs = Blog::where('slug', $slug)
->get();
return View::make('pages.blog')
->with('blogs', $blogs);
}
¹除非你使用了一些更高级的路由功能,否则这不是重点。
²可以使用where子句,但如果你想考虑所有大写/小写组合,那将会很难看。例如:([Jj][Aa][Nn][Uu][Aa][Rr][Yy]|[Ff][Ee][Bb][Rr][Uu][Aa][Rr][Yy]|...)