Displaying product variants - laravel

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);

Related

how to store select/option inside a foreach in a database?

I have a foreach for questions, inside that foreach I print the questions and below I place a select/option
#foreach ($questions as $index => $question)
<p>{{$question->title}}</p>
<p>{{$question->id}}</p>
<select wire:model="answers" name="question" id="question">
<option value="" selected></option>
<option value="yes">YES</option>
<option value="no">NO</option>
</select>
#endforeach
output foreach
I am trying to save all the answers in a database table, in the select I put a wire:model="answers" linked to an array inside the component public $answers=[]; to capture the answers
How can I capture all the answers of the selects, and then store all in the database?
got it, you need to remove any unnecessary attribute and in the select you need to pass the $index to the array wire:model="answers.{{$index}}"

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

How to fix Namespace Laravel selection issue error= '#if(Auth' is not bound

I have this piece of code that I did not write, but need to trouble shoot. The user is supposed to have the choice to pick one, two, or all 3 selections, but no matter what we select, nothing is working. It is giving me an error message of "Namespace '#if(Auth' is not bound".
Here is the code that seems to be the root of the problem.
<select id="dates-field2" class="multiselect-ui form-control" multiple="multiple" name="service_type[]" id="service_type">
#foreach(get_all_service_types() as $type)
<option #if(Auth::guard('provider')->user()->service->service_type->id == $type->id) selected="selected" #endif value="{{$type->id}}">{{$type->name}}</option>
#endforeach
</select>

Laravel Validation - how to return the same category and subcategory that had been selected?

Good evening, I'm developing a form that contains categories and subcategories, the subcategories only appear after the category has been selected. So far so good, when the form is submitted and contains some validation error handled by the validation method, the system returns to the form screen with all the fields except the sub category field that is requested when the category is chosen. ..
How do I do when an error occurs and return to the form screen come with the same subcategory options that had been selected?
Note: I have a provider that sends the categories to the view, but I do not know how to retrieve the category_id to send the subcategories, nor do I know if this would be the best way ...
try this
<select class="form-control" name="warehouse_id" id="_source">
<option disabled="" selected="">Selecciona Almacén</option>
#foreach($warehouses as $warehouse
<option value="{{ $warehouse->id }}" #if(old('warehouse_id') == $warehouse->id) {{ "selected=''" }} #endif>{{ $warehouse->name }}</option>
#endforeach
</select>

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

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>

Resources