试图显示给定类别中的所有帖子 - 获取错误

时间:2017-12-09 00:56:05

标签: php laravel laravel-5

我正在构建我的第一个laravel应用程序。

我试图显示x类别中的所有帖子。

我的路线:

Route::get('/', 'PostsController@index')->name('home');
Route::get('/{id}/{slug?}', 'PostsController@show')->name('show');
Route::get('/categories/{category}', 'CategoriesController@index')->name('category');

我的分类模型:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    public function getRouteKeyName()
    {
        return 'slug';
    }
}

我的类别控制器:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Category;

class CategoriesController extends Controller
{
    public function index(Category $category)
    {
        $posts = $category->posts;

        return view('index', compact('posts'));
    }
}

获取:"抱歉,找不到您要查找的页面。"

如果我改变则可以工作:

Route::get('/{id}/{slug?}', 'PostsController@show')->name('show');

要:

Route::get('/{post}', 'PostsController@show')->name('show');

提前谢谢!

3 个答案:

答案 0 :(得分:0)

这听起来像是配置不正确的路线,有时您定义路线的顺序可能会导致问题。

尝试按照顺序定义路线,而不是看它是否有所不同:

Route::get('/{id}/{slug?}', 'PostsController@show')->name('show');
Route::get('/', 'PostsController@index')->name('home');
Route::get('/categories/{category}', 'CategoriesController@index')->name('category');

答案 1 :(得分:0)

您的路线/{id}/{slug?}正则表达式正在捕获您其他路线的categories字,并阻止其按预期工作。这里有2个选项:

  • categories/{category}移至帖子路线。 Laravel路线在第一场比赛中停止。
  • 定义{id}可以是什么

    Route::get('/{id}/{slug?}', 'PostsController@show')->name('show')->where('id', '[0-9]*');
    

无论如何,如果那个post id路由是后端路由,我建议你像posts/{id}/{slug?}那样加前缀。如果它是前端,请选择以前的解决方案之一(甚至两者)。

答案 2 :(得分:0)

如果类别和帖子之间存在多对多关系或一对多关系,则可以这样做。

Route::get('categories/{category_slug?}',['as'=>'category.show','uses'=>'CategoriesController@Show'})

并在您的控制器中;

 public function Show($category_slug){

        $category = Category::where('category_slug',$category_slug)->first();


        return view('index',compact('category'));
    }

并在你的刀片中;

@foreach($category->posts as $post)
  $post->title
  $post->content
@endforeach
相关问题