I made a filter to find businesses
There are several cities to choose from
Cities store on city_id column
The filter looks like this
<select id="city" multiple name="city[]">
#foreach($cities as $city)
<option value="{{ $city->name }}">{{ $city->name }}</option>
#endforeach
</select>
All request
dd($request->all())
shows me this
I build query for franchise or business
like this
if ($request->has('fb')) {
$businessesQuery->where('fb', $request->fb);
}
I try to build query like this but it's not works
if ($request->has('city[]')) {
$typeArray = explode(",", $request->city[]);
$businessesQuery->whereIn('city_id', $typeArray);
}
Help me solve this issue, I would be very grateful!
Your html must use city_id as a value and not the city name. Because you're trying to search using the id not name.
<option value="{{ $city->id }}">{{ $city->name }}</option>
explode function takes a string as in input and returns an array. In your case your city[] request value is already an array visible from the dump. You should use it directly. Something like this.
if ($request->has('city')) {
$businessesQuery->whereIn('city_id', $request->input('city');
}
Is that possible to get data from other table?
Let say in create table, I get all the info from genre table and display all data in drop down list
<select name="mov_genre" id="mov_genre" class="form-control input-sm">
<option value="">类型</option>
#foreach(App\Genre::all() as $gData)
<option value="{{$gData->gen_title}}">{{$gData->gen_title}}</option>
#endforeach
</select>
In edit page, I want to display it as well but how to display it as the genre I selected when create?
In my opinion, you should use $gData->id as value of each option. Because normally you store the id as foreign key and not something like the title.
But to your question itself: You can simply add an if statement that checks within the foreach loop if the current item is the selected one. In my example I assume you have a variable $movie which is the entry you want to edit.
<select name="mov_genre" id="mov_genre" class="form-control input-sm">
<option value="">-- SELECT GENRE --</option>
#foreach(App\Genre::pluck('gen_title', 'id') as $key => $value)
<option value="{{ $key }}" {{ optional($movie)->genre_id === $key ? 'selected' : '' }}>{{ $value }}</option>
#endforeach
</select>
Please note that I swapped App\Genre::all() for App\Genre::pluck('gen_title', 'id'). This will only load the both fields gen_title and id and put them in an array where id is the key and gen_title the value. It is done for better performance as we do not load unnecessary data.
Also note that optional($movie) will return null when $movie is not set. This is done to reduce weird if statements and is common practice.
I am able to generate the select list in Laravel Way, But how can i insert a custom element in it.
Here is my form:
<li>
<?php
$countrya[] = 'Country';
?>
#foreach($countries as $row)
<?php
$countryarr[$row->CountryID] = $row->Country;
?>
#endforeach
{{ Form::select('ClientSales', $countryarr, '',
array('class' => 'choiceSelect fi_top', 'id' => 'CountryName')); }}
</li>
Here it will generate the list of countries,
The problem is it will display the first country name in the first list, but i want to insert a dummy value inside it.
i.e., <option value="">Choose any Country</option>
How can I do this in Laravel ?
The problem here is:
$countrya[] = 'Country';
I don't know what it's and if you use it, but you need here (after / before above line or instead of it):
$countryarr[''] = 'Choose any Country';
because you use $countryarr in your select. You should also create array with data to View rather in controller and not in Blade template
Check This one
<li>
<?php
$countrya[] = 'Country';
$countryarr[0]='Choose any Country'; //Here is the code I have added
?>
#foreach($countries as $row)
<?php
$countryarr[$row->CountryID] = $row->Country;
?>
#endforeach
{{ Form::select('ClientSales', $countryarr, '', array('class' => 'choiceSelect fi_top', 'id' => 'CountryName')); }}
</li>
Well you have to make your initial item for $countryarr
$countryarr = ['Choose any Country'];
It will create <option value="0">Choose any Country</option>
So its ID will become zero. Its up to you now how you will evaluate the zero when you submit it.
I'm relatively new to Laravel (and using Laravel 4), but been around PHP and C# a long time. Seems like this should be easy, but I can't find anywhere that tells me how to do this.
In my Controller I get the data from the database and send it to the view like this:
$sections = DB::table('paperSections')->lists('section','id');
return View::make('layouts.publisher.step2', array('sections' => $sections));
in my View, I have the following:
{{ Form::select('sections[]', $sections, '', array('multiple')) }}
which generates a select list like this:
<select multiple="multiple" id="sections" name="sections">
<option value="1">News</option>
<option value="2">Sports</option>
<option value="3">Features</option>
<option value="4">Arts and Entertainment</option>
<option value="5">Technology and Science</option>
<option value="6">Op-Ed</option>
</select>
Lets assume I have a string (e.g. "1,3,5") which represents the multiple options selected previously. How can I re-select those three options using that string?
Pass array of selected options as 3rd param:
$selected = explode(',', $idsAsString);
Form::select('sections[]', $sections, $selected, ['multiple'])
One of the requirements in an application that I am building is for a form input which takes in a varying number of items for a single field. For instance, sports that I play are ('Soccer','Tennis','Croquet').
There are a finite number of sports one can play (arguably), so these items should be selected from a "drop down" type list in the form input.
Downstream of this form will be two tables which have a one-to-many relationship. So from the above, the "user" table would have a single row, while the "user_sports" table would have three rows. These would then be linked by the id field in the user table.
I have not been able to find the sort of functionality where this can be achieved in the documentation (perhaps I am not searching for the correct thing). Below was the closest that I found, but is only for selecting a single item from a drop down list.
http://laravel.com/docs/html#drop-down-lists
Is there a workaround out there that will enable me to get this form element up and running using the Laravel framework?
Alternatively, are there other ways that this sort of functionality can be achieved, without damaging the user experience?
I agree with user3158900, and I only differ slightly in the way I use it:
{{Form::label('sports', 'Sports')}}
{{Form::select('sports',$aSports,null,array('multiple'=>'multiple','name'=>'sports[]'))}}
However, in my experience the 3rd parameter of the select is a string only, so for repopulating data for a multi-select I have had to do something like this:
<select multiple="multiple" name="sports[]" id="sports">
#foreach($aSports as $aKey => $aSport)
#foreach($aItem->sports as $aItemKey => $aItemSport)
<option value="{{$aKey}}" #if($aKey == $aItemKey)selected="selected"#endif>{{$aSport}}</option>
#endforeach
#endforeach
</select>
#SamMonk your technique is great. But you can use laravel form helper to do so. I have a customer and dogs relationship.
On your controller
$dogs = Dog::lists('name', 'id');
On customer create view you can use.
{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, null, ['id' => 'dogs', 'multiple' => 'multiple']) }}
Third parameter accepts a list of array a well. If you define a relationship on your model you can do this:
{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, $customer->dogs->lists('id'), ['id' => 'dogs', 'multiple' => 'multiple']) }}
Update For Laravel 5.1
The lists method now returns a Collection.
Upgrading To 5.1.0
{!! Form::label('dogs', 'Dogs') !!}
{!! Form::select('dogs[]', $dogs, $customer->dogs->lists('id')->all(), ['id' => 'dogs', 'multiple' => 'multiple']) !!}
Laravel 4.2
#SamMonk gave the best alternative, I followed his example and build the final piece of code
<select class="chosen-select" multiple="multiple" name="places[]" id="places">
#foreach($places as $place)
<option value="{{$place->id}}" #foreach($job->places as $p) #if($place->id == $p->id)selected="selected"#endif #endforeach>{{$place->name}}</option>
#endforeach
</select>
In my project I'm going to have many table relationships like this so I wrote an extension to keep it clean. To load it, put it in some configuration file like "app/start/global.php". I've created a file "macros.php" under "app/" directory and included it in the EOF of global.php
// app/start/global.php
require app_path().'/macros.php';
// macros.php
Form::macro("chosen", function($name, $defaults = array(), $selected = array(), $options = array()){
// For empty Input::old($name) session, $selected is an empty string
if(!$selected) $selected = array();
$opts = array(
'class' => 'chosen-select',
'id' => $name,
'name' => $name . '[]',
'multiple' => true
);
$options = array_merge($opts, $options);
$attributes = HTML::attributes($options);
// need an empty array to send if all values are unselected
$ret = '<input type="hidden" name="' . HTML::entities($name) . '[]">';
$ret .= '<select ' . $attributes . '>';
foreach($defaults as $def) {
$ret .= '<option value="' . $def->id . '"';
foreach($selected as $p) {
// session array or passed stdClass obj
$current = #$p->id ? $p->id: $p;
if($def->id == $current) {
$ret .= ' selected="selected"';
}
}
$ret .= '>' . HTML::entities($def->name) . '</option>';
}
$ret .= '</select>';
return $ret;
});
Usage
List without pre-selected items (create view)
{{ Form::chosen('places', $places, Input::old('places')) }}
Preselections (edit view)
{{ Form::chosen('places', $places, $job->places) }}
Complete usage
{{ Form::chosen('places', $places, $job->places, ['multiple': false, 'title': 'I\'m a selectbox', 'class': 'bootstrap_is_mainstream']) }}
A multiple select is really just a select with a multiple attribute. With that in mind, it should be as easy as...
Form::select('sports[]', $sports, null, array('multiple'))
The first parameter is just the name, but post-fixing it with the [] will return it as an array when you use Input::get('sports').
The second parameter is an array of selectable options.
The third parameter is an array of options you want pre-selected.
The fourth parameter is actually setting this up as a multiple select dropdown by adding the multiple property to the actual select element..
This might be a better approach than top answer if you need to compare 2 output arrays to each other but use the first array to populate the options.
This is also helpful when you have a non-numeric or offset index (key) in your array.
<select name="roles[]" multiple>
#foreach($roles as $key => $value)
<option value="{{$key}}" #if(in_array($value, $compare_roles))selected="selected"#endif>
{{$value}}
</option>
#endforeach
</select>
My solution, it´s make with jquery-chosen and bootstrap, the id is for jquery chosen, tested and working, I had problems concatenating #foreach but now work with a double #foreach and double #if:
<div class="form-group">
<label for="tagLabel">Tags: </label>
<select multiple class="chosen-tag" id="tagLabel" name="tag_id[]" required>
#foreach($tags as $id => $name)
#if (is_array(Request::old('tag_id')))
<option value="{{ $id }}"
#foreach (Request::old('tag_id') as $idold)
#if($idold==$id)
selected
#endif
#endforeach
style="padding:5px;">{{ $name }}</option>
#else
<option value="{{ $id }}" style="padding:5px;">{{ $name }}</option>
#endif
#endforeach
</select>
</div>
this is the code por jquery chosen (the blade.php code doesn´t need this code to work)
$(".chosen-tag").chosen({
placeholder_text_multiple: "Selecciona alguna etiqueta",
no_results_text: "No hay resultados para la busqueda",
search_contains: true,
width: '500px'
});
Just single if conditions
<select name="category_type[]" id="category_type" class="select2 m-b-10 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose" tooltip="Select Category Type">
#foreach ($categoryTypes as $categoryType)
<option value="{{ $categoryType->id }}"
**#if(in_array($categoryType->id,
request()->get('category_type')??[]))selected="selected"
#endif**>
{{ ucfirst($categoryType->title) }}</option>
#endforeach
</select>