reply 数据显示混乱

我在article的页面里加了一个按钮,可以打开一个对应文章的单独评论页,但是显示出来的数据莫名其妙的,我对应着数据库看也关联不起来。

article.show 模版

.
.
.
<a class="far fa-comment-alt" href="{{ route('replies.show', $article->id) }}"></a>
.
.
.

replies.show 模版

        <div class="article-rank-header mt-3 pb-3 align-items-center">
            <div class="article-title pt-3">
                <h2>{{ $articles->title }}</h2>
            </div>
            <div class="article-author d-flex justify-content-between align-items-center mt-3">
                <div class="author-avatar">
                    <a href="#" class="d-flex align-items-center">
                        <img src="{{ $articles->user->avatar }}" width="25" height="25" class="rounded-circle mr-1" alt="">
                        <span class="mr-1">{{ $articles->user->nickname }}</span>
                        <span>{{ $articles->updated_at->diffForHumans() }}</span>
                    </a>
                </div>
                <div class="author-focus">
                    <a href="#" class="btn btn-sm btn-primary">+ 关注</a>
                </div>
            </div>
        </div>

路由

Route::resource('/replies', 'RepliesController', ['only' => ['index', 'show', 'create', 'store', 'update', 'edit', 'destroy']]);

controller

public function show(Reply $reply)
    {
        $articles = Article::find($reply->id);
        dd($articles);
        return view('mobile.replies.show', compact('reply','articles'));
    }

controller 这么写,数据是可以调用的,但是这么写对不对,或者好不好呢?$reply->article->title为什么这么写调用出来的是错的呢?或者我要这么用的话,controller要怎么修改

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 2

你的 article.show 模板既然是

route('replies.show', $article->id)

那么路由就不能是资源路由

Route::resource('/replies', 'RepliesController', ['only' => ['index', 'show', 'create', 'store', 'update', 'edit', 'destroy']]);

而应该是

Route::get('replies/{article}', 'RepliesController@show')->name('replies.show');
Route::resource('/replies', 'RepliesController', ['only' => ['index', 'create', 'store', 'update', 'edit', 'destroy']]);

控制器就可以这样

public function show(Article $article)
{
    $replies = $article->replies()->latest()->paginate();

    return view('mobile.replies.show', compact('article', 'replies'));
}
4年前 评论
wongvio (楼主) 4年前

我觉得评论可以放在 ArticlesController

定义路由:

Route::get('articles/{article}/replies', 'ArticlesController@replies')->name('articles.replies');

使用路由:

route('articles.replies', $article);

控制器:

public function replies(Article $article)
{
    $replies = $article->replies()->latest()->paginate();

    return view('articles.replies', compact('article', 'replies'));
}
4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!