How can I specify what I want in the select tag while displaying data from the database

Viewed 15

I am a developer of Laravel I created an edit interface And I want when I click on the edit icon to have the SELECT tag automatically selected with the data that came from the database

This is the controller:

 public function update(Request $request,$id)
    {
        $validated=$request->validate([
            'title'=>'required',
            'description'=>'required',
            'date_news'=>'required',
            'category'=>'required',
            'tag'=>'required'
        ],[
            'title.required'=>'  الرجاء تحديد عنوان الخبر  ',
            'description.required'=> ' الرجاء إدخال وصف الخبر',
            'date_news.required'=>' الرجاء تحديد تاريخ نشر الخبر',
            'category.required'=>'الرجاء إختيار صنف الإعلان ',
            'tag.required'=>'الرجاء اختيار التاغ '
        ]);


            $news = News::find($id);
            $news->title = $request->title;
            $news->description = $request->description;
            $news->date_news = $request->date_news;
            $news->id_category = $request->category;
            // dd($news);
            $news->save();
            $news->tags()->attach($request->tag); // add all tags in tags_news table

            return  redirect()->route('news');

This is the edit view :

<div class="seletag">   
        <h2 class="tagnews"> : حدد التاغات </h2>
    </div>
    <div  class="seletagnews">
        <select   class="widthse" multiple name="tag">
            @foreach ($tags as $item)
            <option   value="{{ $item->id }}" selected> {{ $item->tag }}   </option>
        @endforeach
        </select>
        <span class="valitag"> @error('tag') {{ $message }} @enderror </span>

    </div>

And in the edit view in the select tag, I will display the elements I chose, in other words I want to put a check next to the option I chose in the past

I hope I have asked the question well

1 Answers

If you want to show the selected option already checked, you will have to query the $news object before displaying that view. Then in the html, you will have to add a condition instead of always printing <option value="{{ $item->id }}" selected>.

You will need to check if that $item->id is in the array/collection of selected tag ids for the order. And only if it is in that array/collection, you add that selected in the html.

Related