Laravel

How to display selected options in a multi select drop down in Laravel

How to display selected options in a multi select drop down in Laravel


How to display selected options in a multi select drop down in Laravel

Laravel gives you the option to have default values on drop down boxes. When doing form elements in Laravel you can use normal HTML or the Form helper which generates the HTML. With a multi select drop down list. You can use the jquery select2 or Selectator which can make pretty up your normal multi select drop down into selectable and unselectable little buttons.

In Laravel, the Form helper does not support default values for this. Here you have two options you can either use Javascript to do this for you as described in this youtube tutorial or you can do it in PHP in the controller then display it in the view.

Here we are going to explain to you PHP way to do it.
Firstly let's say you want to add tags from a multi select drop down list to a post.

So you have three tables, the post table, the tag table and the post_tag many to many table.

So in the post controller in the edit function I will place the following code:

$post = Posts::where('slug',$slug)->first();
// get the post values


		$poststags = PostsTag::all()->where('posts_id', '=', $post->id);
		$poststags = $poststags->toArray();

// get the selected tags from the many to many post_table

		$selectedtags = array();
		foreach($poststags as $key => $value){
			$selectedtags[$key] = $value['tag_id'];
		}

// take the array which you get from the toArray(); function and manipulate it even more
		
		$tags =  Tag::all();
		$tags2 = array();
		foreach($tags as $tag){
			if (in_array($tag->id, $selectedtags)) {
			 $tags2[$tag->id] ='<option value="'.$tag->id.'" selected="selected">'.$tag->name.'</option>';
			 } else {
			 $tags2[$tag->id] ='<option value="'.$tag->id.'">'.$tag->name.'</option>';	
			 }	
		}

// loop through the array and insert the html with the selected=selected for the once which was inserted previously

 <select multiple size="6" class="form-control select2-multi"  name="tags[]">
   @foreach($tags as $ktag => $vtag)
     {!! $vtag !!}
   @endforeach
 </select>

// display it in the view

 

Published: 24th November 2016 by

Adverts