How do I call a where function in a Laravel view? - laravel

Is there a way to use a where statement in a view?
In the second select input, I want to list all the makes of vehicles in the previously selected year.
<select data-placeholder=" Year" class="chzn-select year" style="width:70px;" tabindex="1" id="year">
<option value=""></option>
#foreach($data['vehicle_years'] as $vehicle)
<option value="{{ $vehicle->year }}">{{ $vehicle->year }}</option>
#endforeach
</select>
<select data-placeholder=" Year" class="chzn-select year" style="width:70px;" tabindex="1" id="year">
<option value=""></option>
#foreach($data['vehicle_makes'] as $vehicle)
<option value="{{ $vehicle->make }}">{{ $vehicle->make }}</option>
#endforeach
</select>
So maybe something along the lines of:
{{ $vehicle->make->where(...) }}

Yes, you can use where() anywhere in a blade in this way:
{{ $vehicle->where('make', $make)->get() }}
But, if you come up with using eloquent in a view, it means there is something wrong in code design. Here are some suggestions:
After the first select is selected by the user, you need to reload the page with selected make, then, you can use it in where() statement in the code design you have now. If there will be no reload, you cannot state what to put in where(). If you will reload the page, then, actually you do not need to use where() in blade..
If you are panning to use the where() in a loop in view, it is better to load all "vehicles and makes" in the controller (if number of items is not too big), and use them (you may need some js)
Alternatively, you may use AJAX to get list of "make" after the vehicle is selected, as it is mentioned in comments.

!!You should not have both selects as the same ID!!
Remember that PHP code is being generated on the backend before it is sent to the client, so it's not possible to use blade to supply a dynamic list unless you are using AJAX to call a new list based on the year and replace the old one. This is heavy lifting though. If you don't have large amounts of data, I'd suggest using regular jQuery to show/hide those that don't match the correct year (maybe by the year being a class). Even better would be to use Vue.js and use v-if to check if the option matches the year selected above.
See Laracasts - Learn Vue 2 (Episode 6) for more details on that.
Here is a quick version of the jQuery answer:
<select data-placeholder=" Year" class="chzn-select year" style="width:70px;" tabindex="1" id="year">
<option value=""></option>
#foreach($data['vehicle_years'] as $vehicle)
<option value="{{ $vehicle->year }}">{{ $vehicle->year }}</option>
#endforeach
</select>
<select data-placeholder=" Year" class="chzn-select year" style="width:70px;" tabindex="1" id="make">
<option value=""></option>
#foreach($data['vehicle_makes'] as $vehicle)
<option class="{{ $vehicle->year }}" value="{{ $vehicle->make }}">{{ $vehicle->make }}</option>
#endforeach
</select>
<script>
$(function() {
var year = $('select#year');
year.change(function() {
var makes = $('select#make > option');
makes.show(); // shows all
// hides all that don't have the selected year as class
makes.each(function( index ) {
if ( !$(this).hasClass( year.val() ) ) $(this).hide();
});
});
});
</script>

Related

Persist javascript changes alongside Laravel 9 and Livewire 2

I have two select option fields--one with the ID of determined and the other vehicle_type. Determined has 4 options--2 of which should disable the options in the vehicle_type select field. In the console, I see the disabled attribute being added, but because of Livewire, is immediately removed. Any way of persisting my changes and force Livewire not to send updates to the server?
<select wire:model="determined" id="determined"
name="determined">
<option selected value>Please Select</option>
<option value="0">Published HP Figure (DIN)</option>
<option value="1">Measured with Dynojet+Dyno</option>
<option value="2">Measured with Mustang Dyno</option>
<option value="3">Measured with Engine Dynamometer Cell</option>
</select>
<select wire:model="vehicle_type" id="vehicle_type"
name="vehicle_type">
<option selected value>Please Select</option>
<option value="0">Stick shift and 2WD vehicle</option>
<option value="1">Automatic or 4WD Drive</option>
</select>
#push('scripts')
$(document).ready(function() {
$('#determined').on("change", function() {
const dis = $(this).val() == 0 || $(this).val() == 3;
$("#vehicle_type option").prop("disabled",dis)
});
});
#endpush
Use .defer on the wire:model to prevent Livewire from making an ajax request immediately and re-render the component.
<select wire:model.defer="determined" id="determined" name="determined">
<option selected value>Please Select</option>
<option value="0">Published HP Figure (DIN)</option>
<option value="1">Measured with Dynojet+Dyno</option>
<option value="2">Measured with Mustang Dyno</option>
<option value="3">Measured with Engine Dynamometer Cell</option>
</select>

Laravel and selectize add option

I use laravel 5.6 and selectize, everything work great but I won't be able to add option or to set value with jQuery.
Here my code :
var select_user, $select_user;
$select_user = $('#select-user').selectize();
select_user = $select_user[0].selectize;
select_user.addOption({id: 10, name: 'name'});
And my html :
<select id="select-user" name="user" class="form-control" placeholder="Sélectionnez un utilisateur" required>
<option value="">Sans</option>
#foreach($users as $user)
<option value="{{$user->id}}">{{$user->name }}</option>
#endforeach
</select>
I have my users from my bdd but not my added one. No error message too.
Someone can tell me where I'm wrong ?
Thank for your help.

How to show selected value from database in dropdown using Laravel?

I want to show selected value from database into dropdown list on page load.
My controller index function is :
public function index()
{
$country_data =DB::table('country')->select('country_id','country_name')->get();
$profile_data= DB::table('profiles')->select('*')->where('id',$user_id)->first();
return view('profile_update',compact('profile_data','country_data'));
}
Column name in database for height is :Height
My dropdown in profile_update.blade.php is
<select class="select4" name="country" id="country">
<option value="">Please Select</option>
#foreach($country_data as $country)
<option value="{{$country->country_id}}" {{$country_data->country == $country->country_id ? 'selected' : ''}}>{{$country->country_name}}</option>
#endforeach</select>
This is a example of how I do this:
<select class="js-states browser-default select2" name="shopping_id" required id="shopping_id">
<option value="option_select" disabled selected>Shoppings</option>
#foreach($shoppings as $shopping)
<option value="{{ $shopping->id }}" {{$company->shopping_id == $shopping->id ? 'selected' : ''}}>{{ $shopping->fantasyname}}</option>
#endforeach
</select>
In order to understand it fully you will need basics of laravel (MVC),
Let suppose, you have controller. In my case I made a separate table for drop down values.
My Approach --- Separate table for values of drop down, you can try different approach but my explanation was mainly focused on concept.
Note: PersonInfo is model, sampleType is model of my drop down values and don't forget to make a route for the controller.
ExampleController{
public funtion getValues($id){
/*
I am fetching information of a single row from the database by id and
then passing it to the view. The $id to the function came from the
request by your view/form.
I also fetched the values of drop down from the separate table
of database and passed it to the exampleView.
*/
$selectedValue=PersonInfo::findOrFail($id);
$sampleType=SampletypePicker::all(); //model for fetching all values of drop down
return view('exampleView',compact('selectedValue','sampleType));
}
}
So, in the above controller I fetched all values and passed it to the ExampleView. Now in your View file you have to work likewise.
exampleView.blade.php add the below code
<?php $options=$selectedValue->sample_type ?> //note take the value from the database which stored for the individual record and match it with the selected one.
<select class="form-control" name="test">
<option>Select Test Type</option>
#foreach ($sampleType as $value)
<option value="{{ $value->sample_type }}" {{ ( $value->sample_type == $options) ? 'selected' : '' }}>
{{ $value->sample_type }}
</option>
#endforeach
</select>
It is one of the best approach when you want to add dynamic values to the drop down. I mean if you want to add more values to the select tag options then this is the best approach.
Another Approach - take the idea
<?php $months = array("Jan", "Feb", "Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"); ?>
<?php $options=$patient_data->month ?>
#if($patient_data->month)
<select id="expiry_month" name="month" class="form-control-sm">
#foreach($months as $month)
<option value="{{$month}}" {{($month==$options)? 'selected':'' }}>{{$month}}</option>
#endforeach
</select>
#endif
<span class="select-icon"><i class="zmdi zmdi-chevron-down"></i></span>
</div>
OUTPUT of ABOVE CODE
#Sarita Sharma show the error(s). Maybe then anyone help you to resolve this problem. Show data in colections in controler - use dd e.g.
dd($country_data);
dd($profile_data);
Do you want to display the country in the view with the appropriate Height value from profile_data?
Ps. How to put the code, please use the formatting code - put the code in `` and use camelCase in value name (maintaining good PSR-1 practice) - it is easier to read code.
Well, simply if anyone still looking for this, here is the simple way to select items for dropdown from database to blade view
$users = Users::pluck('name', 'id');
$selectedID = 2;
return view('users.edit', compact('id', 'users'));
add this in the controller function before rendering the view
and in the blade view, simply use this variable as foreach loop as
<select name="user_id" class="form-control" id="exampleFormControlSelect1">
#foreach ($users as $key => $value)
<option value="{{ $key }}" {{ ($key == $selectedID) ? 'selected' : '' }}>
{{ $value }}
</option>
#endforeach
</select>
if you don't want to select all users from DB, you can use where condition before pluck condition as
$users = Users::where('status', 1)->pluck('name', 'id');
works with Laravel 8 and Laravel6

Displaying product variants

I have an online store that sells clothes. Each items (ex: T-shirt) have two attributes, colors and sizes. I'm combining the three tables together in a variants table, that has the following structure :
- item_id
- color_id
- size_id
- price
- stock
This works and I'm using a hasMany() relationship between the items and the variants (an item has many variants) and then a belongsTo() relationship between each variants and the colors/sizes (each variants belong to a color and to a size).
Here's the code I'm using to fetch all the items :
$items = Item::with(['variants', 'variants.color', 'variants.size'])->get();
Here's a sample of the returned data : http://pastebin.com/CjsYp6wS
The problem I have is with displaying this data. I want to display each item in a table, and for each item have two select boxes : one that shows all the colors, one that shows all the sizes. The user can then choose a color and a size, and see the updated price for this variant.
However, because of the way my relationships are setup, if I want to display all the colors and all the sizes, I have to do something like this :
<select name="color">
#foreach($item->variants as $variant)
<option value="{{ $variant->color->id }}">{{ $variant->color->name }}</option>
#endforeach
</select>
This is far from ideal, since it results in duplicated values for each colors and sizes if they happen to be in two or more variants.
Is there a better way to do this? I'm thinking that there has to be a simpler way to do it, with a different database structure or Eloquent relationships or something.
You can store all the values you are displaying in an array and check if you have already displayed that value and if you have displayed it, you can skip it. In that case you code should look like:
<select name="color">
<?php $color_array=[]; ?>
#foreach($item->variants as $variant)
#if(!in_array($variant->color->id,$color_array)
<option value="{{ $variant->color->id }}">{{ $variant->color->name }}</option>
<?php array_push($color_array,$variant->color->id); ?>
#endif
#endforeach
</select>
This will make it check if the value entered is already entered in the array before displaying it. If it is not entered, then it will display it and add it into array else it will not do anything and skip to next entry.You can do the same for size or any other attribute also. Hope this helps.
Select the item, get the item_id:
$items=Item::all();
<select name="iem">
#foreach($items as $item)
<option value="{{ $item->id }}">{{ $item->name }}</option>
#endforeach
</select>
Select the color, get the color_id:
$colors=Color::all();
<select name="color">
#foreach($colors as $color)
<option value="{{ $color->id }}">{{ $color->name }}</option>
#endforeach
</select>
Select the size, get the size_id:
$sizes=Size::all();
<select name="color">
#foreach($sizes as $size)
<option value="{{ $size->id }}">{{ $size->name }}</option>
#endforeach
</select>
Fetch the price having that item_id, color_id and size_id from variants table:
$variant=Variant::where[('item_id'=>$item_id)]->where[('size_id'=>$size_id)]->where[('size_id'=>$size_id)]->first();
print_r($variant->price);

codeigniter form_dropdown

how to disable option in drop down box using code igniter?i want to disable the value"------"in this drop down
echo "<tr class='background1'><td class='checkoutfield'>";
$countryall='';
$select='';
if(isset($order)) $country=$order['varShippingCountry']; else $country='';
if(isset($countries) && $countries !='') {
$countryall['']="Select";
foreach($countries as $key=>$value):
$countryall["226/United States"]="United States";
if($value['id'] !='226') {
//<option value=”spider” disabled=”disabled”>Spider</option>
$countryall['0']="-------------------------------------------------------";
$countryall["$value[id]/$value[varPrintableName]"]=$value['varPrintableName'];
}
if($value['id'] == $country)
$select="$value[id]/$value[varPrintableName]";
endforeach;
}
$selFunc='style="width:190px;" id="varShippingCountry" class="required" onchange="stateajax(this.value)" onKeyup="return changeText(\'varShippingCountry\',\'varPaymentCountry\',\'this.value\')"';
echo form_label('Country','varShippingCountry')."<span class='mandatory'>*</span></td><td>";
echo form_dropdown('varShippingCountry',$countryall,$selFunc);
You can't disable an item in a HTML select element - only disable the entire element.
Are you trying to make a separator between different sections of the list? In that case, you can use <optgroup>.
<select>
<optgroup label="Swedish Cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</optgroup>
<optgroup label="German Cars">
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</optgroup>
</select>
You can make this happen in CodeIgniter by passing it a multidimensional array.
Alternatively, if you are just trying to make the first and default item look like ------, then add it in the normal way with an empty value. Then on validation, check that an empty value has not been passed.

Resources