【问题标题】:Display data in the blade from the database从数据库中显示刀片中的数据
【发布时间】:2020-04-15 12:54:28
【问题描述】:

如何在我的视图中的某些表中显示数据库中的数据?没有foreach,因为它会和我重叠。我想获取一个 id,它会显示出来,如果我点击另一个 id,它会显示我想要从另一个 id 得到的东西。以下是我的做法。

控制器:

public function viewUserQuestion() {
    if(Auth::check()) {
        $posts = Post::all();
        return view('viewQuestion', compact('posts'));
    }
    else {
        return redirect('register');
    }
}

刀片:

<div class="card-body p-0">
<div class="mailbox-read-info">
    <h5 align="center">{{ $posts->title }}</h5>
    <h6> From userID: {{ $posts->user_id }}</h6>
    <span class="mailbox-read-time" align="center">Created at: {{ $posts->created_at }}</span></h6>
</div>
<div class="mailbox-read-message">
    <p>{{ $posts->content }}</p>
</div>

我必须说我看过其他类似的问题,但我无法得到提示?

【问题讨论】:

    标签: php html mysql laravel


    【解决方案1】:
    @foreach($posts as $post)
    <div class="card-body p-0">
        <div class="mailbox-read-info">
            <h5 align="center">{{ $post->title }}</h5>
            <h6> From userID: {{ $post->user_id }}</h6>
            <span class="mailbox-read-time" align="center">Created at: {{ $post->created_at }}</span></h6>
        </div>
        <div class="mailbox-read-message">
            <p>{{ $post->content }}</p>
        </div>
    </div>
    @endforeach
    

    编辑:如果您只想返回 1 个帖子,请在您的控制器中使用:

    public function viewUserQuestion() {
        if(Auth::check()) {
            $posts = Post::where('id', 1)->first();
            return view('viewQuestion', compact('posts'));
        }
        else {
            return redirect('register');
        }
    }
    

    【讨论】:

    • 我不想要一个,我想全部退回,但是当我点击帖子中的一个 id 时,它会在显示页面中只显示该 id 的内容。
    • 您的问题是关于在仅指定一个视图时呈现不同的视图。我建议你深入学习这样的教程:laravel.com/docs/5.1/quickstart
    • 是的,但是对于一个特定的 ID 来显示我的数据,我将有一个连续的 ID,如果我点击一个 ID,我想显示我所指的那个 ID .
    【解决方案2】:

    $posts 是一个集合,因此您必须对其进行迭代 - 示例:

    <div class="card-body p-0">
    @foreach($posts as $post)
      <div class="mailbox-read-info">
        <h5 align="center">{{ $post->title }}</h5>
        <h6> From userID: {{ $post->user_id }}</h6>
        <span class="mailbox-read-time" align="center">Created at: {{ $post->created_at }}</span></h6>
      </div>
      <div class="mailbox-read-message">
        <p>{{ $post->content }}</p>
      </div>
    @endforeach
    </div>
    

    【讨论】:

    • 如果我使用@foreach,我将显示我的数据,例如来自两个不同 ID 的两次。
    • 您返回数据库中的所有帖子。您也可以保持视图不变并使用Post::first(); 而不是Post::all();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 2021-09-22
    • 2020-08-19
    • 2016-04-04
    • 2020-07-26
    • 2016-09-15
    • 2021-01-07
    相关资源
    最近更新 更多