In a laravel controller I currently have these two variables which are pulling from a their respective models.
$guests = Person::where('id', $id)
->with('languages')
->get();
$languages = Language::pluck('name')->toArray();
return view('layouts.visitor', ['guests' => $guests, 'languages' => $languages]);
in the database table I have a few different fields:
id | name
----------
1 | spanish
2 | english
3 | french
When selecting a language I'm able to select a language assigned to a user. I am also able to select all the languages in the table. What I would like to do and I'm not able to figure out is to have it show the current language assigned to a user first when he page loads then after if the user would like to change it they should view all the OTHER languages available in the drop down.
If the default language for this user was spanish it should be like this:
Drop down:
Spanish
English
French
You can add the selected attribute to the dropdown option if that is the user's chosen language:
<select name="language">
#foreach($languages as $language)
<option value="{{$language->id}}" #if($user->language_id == $language->id) selected #endif>{{$language->name}}</option>
#endforeach
</select>
I assume you are using one to many relationship. And your persons table has a language_id column which is foreign key of languages table.
In that case your controller should look like this:
public function show($id){
$guests = Person::query()->findOrFail($id); //find a row with an id
$languages = Language::pluck('name','id'); //'name' is the value and 'id' the key of the array
return view('layouts.visitor', ['guests' => $guests, 'languages' => $languages]);
}
Blade:
In blade keep the default value null. It will retrieve the value of language_id column from database.
{{ Form::select('language_id',$languages,null,['otherAttribute'=>'ifAny']) }}
The third parameter of the select method is responsible for selecting the current related property. So like smartrahat answer, you will correct your pluck to be ..pluck('name','id') then in view:
{{ Form::select('language_id',$languages,$guests->language,['class' => 'form-control']) }}
This solution assumes that there a property for Person model named language and it should be the language id integer.
Related
I'm trying to figure out how I can structure my Laravel select menu so that it shows up as this for a final render. Has anyone done such a thing.
The location is a property of the arena object.
<option value="arena_id">Arena Name - Location</option>
{{ Form::select('arena_id', [ null => 'Please Select'] + $arenas, null, ['id' => 'arena_id']) }}
I asssume $arenas comes from something like Arena::where('foo', bar)->get(), but with get() you will get an instance of Illuminate\Database\Eloquent\Collection instead of an actual array which is what you want in Form::select.
So what you need to do is to use lists($field, $key), it will fetch you rows and return it as an array.
$arenas = Arena::where('foo', bar)->lists('name', 'id');
There is a code example here with some comments from users if you want to learn more.
You can use pluck function for getting the results as array
refer https://laravel.com/docs/5.1/collections#method-pluck
$select = $this->all()->pluck('title', 'id');
Then you can use below sample code for creating select box with selected option in blade template
{{ Form::select('name',$select,'selected option id',['class' => 'form-control']) }}
I'm trying to use blade to display a dropdown list from table data. The problem I have, is that I want to display the results of two fields in the table concatenated, not just one.
So I want something to render something like;
<select id="agreement_type" name="agreement_type">
<option value="1">Agreement Field 1 - Agreement Field 2</option>
<option value="2">Agreement Field 1 - Agreement Field 2</option>
<option value="4">Agreement Field 1 - Agreement Field 2</option>
</select>
My controller currently looks like this;
$agreements = Agreement::lists('agreement_type','id');
return View::make('client_agreements.create')
->with('agreements', $agreements);
My blade view currently looks like this;
<div class="form-group">
{{ Form::label('agreement_type', 'Agreement type') }}
{{ Form::select('agreement_type', $agreements) }}
</div>
I have tried to amend the view and controller in various ways to get the desired output. But can't get it to work.
I want to display agreement_type and level and have the id set as the value so I tried;
$agreements = Agreement::lists('agreement_type'.'level','id');
But this just displays level as the value and completely ignores id.
This is the simplest method. Just use a foreach loop to build the options array:
$agreements = Agreement::all();
$agreementOptions = array();
foreach($agreements as $agreement){
$agreementOptions[$agreement->id] = $agreement->agreement_type.' '.$agreement->level;
}
return View::make('client_agreements.create')
->with('agreements', $agreementOptions);
However you can also define an attribute accessor in your model. You can use that to create new properties that can be accessed normal, but you can run logic to generate them (like combining to attributes)
public function getSelectOptionAttribute(){
return $this->attributes['agreement_type'].' '.$this->attributes['level'];
}
And then you can use lists:
$agreements = Agreement::all()->lists('select_option', 'id');
(Laravel converts SelectOption (studly case) from the method name to select_option (snake case) for the attribute, so don't get confused by that)
I'm using Laravel framework and i have two dropdown lists of which both are reading data from the database tables,
the first one it read all the records from the table and populate it on the select list
here is my code:
<div class="form-group">
{{Form::select('advertiserName', Advertiser::all()->lists('advertiserName', 'advertiserId'))}}
</div>
it display the advertiser name and also passes the id on the advertiser.
The second dropdown i want it to display all the Brands related to the above selected advertiser.
here is my code:
<div class="form-group">
{{Form::select('brandName', Brand::where('advertiserId', '=', '3')->lists('brandName', 'id'))}}
</div>
The advertiserId is the foreign key of the advertiser and 3 must be replaced by the the advertiserId you selected on the first dropdown list, basically i want to pass variable from the first select list to the second one
Thank you
Basically you need to use AJAX to get data for Second Dropdown based on option selected from first dropdown.
Create Second Dropdown inside specific div and After ajax Call replace contect of div from ajax response.
As stated, the best way to achieve this is via an AJAX request. Here is an example of how you can achieve this functionality.
Firstly create a view partial that renders the select box for brands. Something like this (this code is based on Bootstrap 3):
{{ Form::label('brandName', 'Brand', ['class' => 'control-label col-sm-2']) }}
<div class="col-sm-10">
{{ Form::select('brandName', $brands, null, ['class' => 'form-control']) }}
</div>
Now, in your routes.php file add the following route:
Route::get('brand-list/{id}', ['as' => 'brands', 'uses' => 'BrandsController#brandList']);
In your BrandsController.php file (or whatever controller your using to handle this) add a method called brandList();
public function brandList($id)
{
// Return an array of brands for the selected advertiser name ID if available
$brands = $this->brand->where('advertiserId', $id)->lists('brandName', 'id'); // I'm using dependency injection here so you'll need to assign your Brand model to the $this->brand property of this classes constructor method
if ( ! isset($brands))
{
$brands = ['No brands available' => null]; // return a generic array containing 1 item with a value of null so you can handle it in your view. You could also return something else here such a boolean of false and then handle that in your AJAX request to return an error or info message
}
return View::make('brands.partials.select', compact('brands'));
}
Now for the AJAX:
$('#advertiserName').change(function(e) {
var advertiserId = $(this).val();
var url = '/brand-list/' + advertiserId;
$.get(url, function(data) {
$('.brands').html(data); // The returned view with the brand select input
});
});
Then in your initial form view you'll want to create an empty div with a class of .brands that we'll use to populate with the HTML returned via our AJAX request. Something like this if you're using Bootstrap 3 for example:
<div class="form-group brands"></div>
This should work as you need but I haven't tested this code, so if you have any issues let me know. Obviously this is generic code based on the info available and there are many ways to skin a cat.
I am attempting to create a drop down selection box for various attributes of a product which the user would select on a product page, such as weight or flavour or colour. My database for the products is currently as follows:
products(id,productname,productprice)
productattributes(id,productid,attributename,value)
I'm using Laravel. So far in my controller I have:
public function show($id)
{
$product = DB::table('products')->where('slug', $id)->take(1)->get();
$prodid = DB::table('products')->where('slug', $id)->pluck('id');
$prodattr = DB::table('productattributes')->where('prodid', $prodid)->get();
return View::make('product/singleproduct', ['product' => $product, 'prodattr' => $prodattr]);
}
And in the view I have:
#foreach ($prodattr as $prodattribute)
{{ $attrname = $prodattribute->attributename }}
{{ $attrvalue = $prodattribute->value }}
#endforeach
This gives me the output:
Flavour Unflavoured
Flavour Strawberry
Weight 1kg
So I have the data I need, but my problem is how to get this into a select box for each attribute. I won't always know what the attribute names will be (colour may be added, for example) or how many there will be, so I don't want to hard code 'Flavour' etc in. I essentially want to generate HTML like this:
<select name="flavour">
<option value="Unflavoured">Unflavoured</option>
<option value="Strawberry">Strawberry</option>
</select>
<br>
<select name="weight">
<option value="1kg">1kg</option>
</select>
Does anyone have any ideas? I'm thinking a loop within the loop, or maybe my table layout is less than ideal? I thought about adding another query within the foreach loop, but this seems counterproductive as I think I have all the data I need. I also wondered if it would be possible to combine or merge the arrays somehow? Any help is much appreciated!
You could create a third table in order to seperate custom attributes and available values for each attributes.
Example of structure I would use:
products(id, name, price)
product_meta_name(id, name)
product_meta_value(id, product_meta_name_id, product_id, value)
Here is my Select Box, Here All Company will be loaded,
But i want to display the Particular company as default selected which i have it in session.
Here is my Code
$sessioncompany = 'ABCcompany'
$comp[''] = 'Company';
#foreach($company_list as $row)
<?php
$comp[$row->CompanyID] = $row->CompanyName;
?>
#endforeach
{{ Form::select('CompanyID', $comp, '', array('id' => 'seCompanyID')); }}
What i tried is
{{ Form::select('CompanyID', $comp, '', array('id' => 'seCompanyID'), array(id=>$sessioncompany)); }}
But i ended with failure
What is the mistake i am doing and How can i fix that ?
Note : I want it in the native laravel method
$selectedId = ... // get the id from the session
{{ Form::select('CompanyID', $comp, array($selectedId), array('id' => 'seCompanyID')) }}
The Form::select() method has the following parameters:
$name - the nameHTML attribute
(array) $list - the list of options, key-value pairs for actual value => displayed value
$selected - the selected item's value
(array) $options - any extra HTML attributes, as per other Form/HTML helper methods
So, the third parameter $selected is the one you want to pass your session value to. Copying your example and replacing:
{{ Form::select('CompanyID', $comp, Session::get('my_session_var'), array('id' => 'seCompanyID')); }}
Where 'my_session_var' is the name of the session variable you store the value of the item that should be selected by default.
The great thing about using Laravel's Form helpers is that you get the 'old' input for free. For example, if you set a default here and the user changes it, submits the form and there's a validation error. When the form is redisplayed (assuming you redirected back with return Redirect::back()->withInput();) the value the user selected, rather than your explicit default will be set.
(Thanks to #JarekTkaczyk for putting me right on the old input thing.)
You are passing wrong parameters. max parameters should be 4. Try this:
{{ Form::select('CompanyID', array('default' => $sessioncompany)+$comp, 'default') }}
Just beware, if you're on a page with the form with the select box, make sure that with each page refresh while testing you do a full page refresh without using cache - Ctrl + Shift + R, otherwise the last selected value may remain selected.