使用php预选选择选项

I've a form to be completed to create a post. Now after creating that post, if I want to edit it, I'm showing a select option in the edit page something like below. (I am using Laravel)

<select name="posts">
@foreach($posts as $post)

  <option value="{{$post->id}}"> {{$post->name }} </option>

@endforeach
</select>

Now I need to preselect the populated select field with the current post name. I have a post id in the URL which I can get know in which post I am in. How can I select the right option without making a duplicate of the same in the options field. ?

Use an if-else structure inside the loop.

if ( post is equal to the current post ) {
     <option selected="selected" value="{{$post->id}}"> {{$post->name }} </option>
} else {
    <option value="{{$post->id}}"> {{$post->name }} </option>
}

The condition depends on you, whether you want to use the post id or the post name to check. (Whatever you have available).

Assuming you pass the current post id into the template as $postId, you could do something like this:

<select name="posts">
@foreach($posts as $post)

    <option value="{{$post->id}}" {{ ($post->id == $postId) ? 'selected="selected"' : '' }}> {{$post->name }} </option>

@endforeach
</select>

Also, since you're using Laravel, a little bit cleaner solution is to use Laravel's Form builder:

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