Question:
I’m creating a blog for Laravel App where only admins can post new articles/posts to the blog. In the posts I made an option for the admins to choose who’s the author of the post however I’m trying the set the default selected author is the current admin when creating a new post while the edit page it retrieves the author from the database and set it as default.In the controller I called all the admins to list in them in blade
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$authors = Admin::all();
$categories = Category::all();
$tags = Tag::all();
return view('posts.create', compact('categories', 'tags', 'authors'));
}
Than in blade I’m setting a condition where it says if the author_id is not set let the current logged-in admin be the default chosen author. <select name="author" id="author" data-placeholder="Choose an Author" class="form-select">
@foreach($authors as $author)
<option value="{{$author->id}}"
@if (!isset($post->author_id))
{{ auth()->guard('admin')->user()->id ? 'selected' : '' }}
@elseif ((isset($post->author_id) && $author->id == $post->author_id))
{{ 'selected' }}
@endif>{{ $author->name }}</option>
@endforeach
</select>
The above code adds selected to all options and calls the last one in the options.Answer:
You need to check ifAuth ID
equals to Select ID
<select name="author" id="author" data-placeholder="Choose an Author" class="form-select">
@foreach($authors as $author)
<option value="{{$author->id}}"
@if (!isset($post->author_id))
@if(auth()->guard('admin')->user()->id=={{$author->id}})
Selected
@endif
@elseif ((isset($post->author_id) && $author->id == $post->author_id))
{{ 'selected' }}
@endif>{{ $author->name }}</option>
@endforeach
</select>
OR You can do something like this<select name="author" id="author" data-placeholder="Choose an Author" class="form-select">
@foreach($authors as $author)
<option value="{{$author->id}}"
@if (!isset($post->author_id))
{{ auth()->guard('admin')->user()->id == {{$author->id}} ? 'selected' : '' }}
@elseif ((isset($post->author_id) && $author->id == $post->author_id))
{{ 'selected' }}
@endif>{{ $author->name }}</option>
@endforeach
</select>
If you have better answer, please add a comment about this, thank you!
Source: Stackoverflow.com
Leave a Review