在数据库中显示刀片中的数据

时间:2020-04-02 11:01:05

标签: php html mysql laravel

如何在视图中的某些表中显示数据库中的数据?没有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>

我必须说我已经看过类似的其他问题,但是我没有小费?

2 个答案:

答案 0 :(得分:0)

@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');
    }
}

答案 1 :(得分:0)

$ 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>