Return 将用户的帖子记录到 laravelcollective/html Select 表单中的下拉菜单
Return Logged User's Posts Into laravelcollective/html Select Dropdown Menu Within a Form
我试图仅将登录用户创建的帖子传递到表单中的 laravelcollective/html select 下拉菜单中。
在我的代码中有两个示例。使用变量 example 展示了我如何获得下拉菜单 select 以显示帖子 table 的所有结果。在 foreach 循环中使用变量 posts 显示了我如何 return 仅由登录用户创建的帖子,而不是在 select 菜单中。
我需要像使用 example 的表单一样具有下拉菜单功能,但显示 foreach posts 循环的结果。
控制器
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
尝试$posts = Posts::where('user_id',\Auth::id())->get()->pluck('title','');
。它将 return 仅登录用户的帖子。
{{ Form::select('example', $posts) }}
您使用的 select 盒子有误。
@foreach($posts as $post)
@if(Auth::user()->id == $post->user_id)
{{ $post->title }} <br>
@endif
@endforeach
如果 Auth::user()->id == $post->user_id
,我会将您的控制器更新为仅 return 用户的帖子,而不是依赖 foreach 检查
public function createPost()
{
$posts = Posts::where('user_id', auth()->user()->id)->get();
return view('post.create', compact('posts'));
}
附带说明一下,您的方法可能应该只是 create()
以与标准 CRUD 保持一致。
然后在您的 blade、
<div class="form-group">
{!! Form::label('post', 'Posts:') !!}
{!! Form::select('post', ['' => 'Select'] + $posts, null) !!}
</div>
我试图仅将登录用户创建的帖子传递到表单中的 laravelcollective/html select 下拉菜单中。
在我的代码中有两个示例。使用变量 example 展示了我如何获得下拉菜单 select 以显示帖子 table 的所有结果。在 foreach 循环中使用变量 posts 显示了我如何 return 仅由登录用户创建的帖子,而不是在 select 菜单中。
我需要像使用 example 的表单一样具有下拉菜单功能,但显示 foreach posts 循环的结果。
控制器
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
尝试$posts = Posts::where('user_id',\Auth::id())->get()->pluck('title','');
。它将 return 仅登录用户的帖子。
{{ Form::select('example', $posts) }}
您使用的 select 盒子有误。
@foreach($posts as $post)
@if(Auth::user()->id == $post->user_id)
{{ $post->title }} <br>
@endif
@endforeach
如果 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 保持一致。
然后在您的 blade、
<div class="form-group">
{!! Form::label('post', 'Posts:') !!}
{!! Form::select('post', ['' => 'Select'] + $posts, null) !!}
</div>