将记录用户的帖子返回到laravelcollective / html选择表单中的下拉菜单

问题描述 投票:0回答:2

我试图只将登录用户创建的帖子传递到表单中的laravelcollective / html选择下拉菜单。

在我的代码中,我有两个例子。使用变量示例显示了如何获取下拉选择菜单以显示posts表中的所有结果。在foreach循环中使用变量posts显示了我如何只返回由已登录用户创建的帖子,而不是在选择菜单中。

我需要使用示例中的下拉菜单功能,但显示foreach帖子循环的结果。

调节器

public function createPost() 
{
  $example = Post::pluck('title', 'id')->all();
  $posts = Posts::all();

  return view('post.create', compact('posts', 'example'));
}

示例视图

<div class="form-group">
  {!! Form::label('example', 'Posts:') !!}
  {!! Form::select('example', ['' => 'Select'] + $example, null) !!}
</div>

Foreach循环帖子视图

@foreach($posts as $post)
  @if(Auth::user()->id == $post->user_id)
    {{ $post->title }} <br>
  @endif
@endforeach
laravel laravelcollective
2个回答
3
投票

试试$posts = Posts::where('user_id',\Auth::id())->get()->pluck('title','');。它只返回登录用户的帖子。

{{ Form::select('example', $posts) }}

您使用选择框错误。

@foreach($posts as $post)
  @if(Auth::user()->id == $post->user_id)
    {{ $post->title }} <br>
  @endif
@endforeach

3
投票

我会更新你的控制器只返回用户的帖子,而不是依赖foreach检查Auth::user()->id == $post->user_id

public function createPost()
{
  $posts = Posts::where('user_id', auth()->user()->id)->get();

  return view('post.create', compact('posts'));
}

作为旁注,你的方法应该只是create()以保持与标准CRUD内联。

然后在你的刀片中,

<div class="form-group">
  {!! Form::label('post', 'Posts:') !!}
  {!! Form::select('post', ['' => 'Select'] + $posts, null) !!}
</div>
© www.soinside.com 2019 - 2024. All rights reserved.