How to show selected value from database in dropdown using Laravel? - 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

Related

how to add multiple roles to user_role in one cell (LARAVEL 8x)

Hi im bad at explaining so bare with me please :)
I got roles users and user_role. i currently have a multi-select-box to assign a user a role, but the user_role only saves one role_id from the select-boxes .
My questions:
How can i save multiple role_id in one cell in user_role?
How do i check if user has a duplicate role in the database?
--
My UserRoleController#Store
public function store(UserRoleStoreRequest $request)
{
$validated = $request->validated();
$roles_ar = $validated['role_id'];
$roles="";
foreach($roles_ar as $key => $role){
if (isset($role)){
$roles.= $key . $role . ',';
};}
// dd($roles);
$user = User::find($validated['user_id']);
$user->roles()->attach([$roles]);
return redirect('/user-role');
}
connect.blade.php (Multi-select-input-box)
<select class="form-control" name="user_id">
<option value="" selected="selected"></option>
#if($users)
#foreach($users as $user)
<option value="{{ $user['id'] }}" ><h3>{{ $user['name'] }}</h3></option>
#endforeach
#endif
</select>
<label class="description">Role</label>
<div class="form-group">
<label for="exampleFormControlSelect2">Use CTRL to multiselect</label>
<select multiple class="form-control" id="exampleFormControlSelect2" name="role_id[]">
#if($roles)
#foreach($roles as $role)
<option value="{{ $role['id'] }}" ><h3>{{ $role['name'] }}</h3></option>
#endforeach
#endif
</select>
To attach multiple roles to a user, you can call attach method and provide an array of IDs as an argument. Since you already have an array of IDs from the input in variable $roles_ar, then you can call attach like so.
$user->roles()->attach($roles_ar);
You also asked how to check for duplicates of roles in the database. But you don't have to check for duplicates if you remove all the existing roles in the database then attach all the new ones. So you should call detach method first before calling attach method above.
$user->roles()->detach();
Thanks to #brombeer you can use sync() instead of calling detach() then attach()
$user->roles()->sync($roles_ar);

How to avoid checking every time, if variable is set in blade template? Laravel 8

I know about something like this:
{{ old('contents', $page->contents ?? null) }}
But what about more complicated cases, like checkboxes and selects?
<select id="custom_template" name="custom_template">
{{--default empty option, if nothing is selected yet--}}
<option label=" " {{ ($page->custom_template == null)? "selected" : "" }}></option>
#foreach($templates as $template)
<option value="{{ $template->id }}" {{ ($page->custom_template == $template->id)? "selected" : "" }}>{{ $template->name }}</option>
#endforeach
</select>
I need to avoid checking #isset($page) and also check old input. How can I do it in that select input?
You can use Type hinting to avoid the 'isset'.
Your controller
/**
* Show the form for creating a new resource.
*
* #param \App\Entities\Page $page
*
* #return \Illuminate\View\View
*/
public function create(\App\Entities\Page $page)
{
return view('page', compact('page'));
}
With using 'Type hinting' in create function will create empty collection of Page Entities. No need to check isset condition in view, $page->custom_template will give you null now, instead of error.
And your view, to check the old input.
<select id="custom_template" name="custom_template">
<option value="">Select Option</option>
#foreach($templates as $template)
<option value="{{ $template->id }}" {{ (old('custom_template', $page->custom_template) == $template->id) ? 'selected' : '' }}>{{ $template->name }}</option>
#endforeach
</select>
By using the above condition you can use same view for create and edit function.
Hope, this will solve your problem.
I'm not sure I quite understand what you're trying to do but this approach may help; provided you're using JQuery:
<script>
$(document).ready(function() {
#if($page->custom_template)
$('option[value="{{ $page->custom_template}}"]').prop("selected", true);
#endif
});
</script>

Laravel search-filter

I have a problem with passing the selected index to my controller via click.
If I manually change the index in the browser, it is working.
(http://localhost:3000/admin/users?user=&sortBy=5)
$sortOptions is the name of my 2d array in my controller.
sortDisplay is a field in my 2d array in my controller.
Am I missing something in my foreach loop?
<label for="sortBy">Sort by</label>
<select class="form-control" name="sortBy" id="sortBy">
#foreach($sortOptions as $index => $sortOptions)
<option value="{{$index}}" {{ (request()->sortBy == $index ? 'selected' : '') }}>
{{$sortOptions["sortDisplay"]}}
</option>
#endforeach
</select>
Use jQuery to submit form when value changed
So your page will refresh and you will get what you want
In the foreach loop, you are assigning the same variable name as the variable you are iterating. In your case, after the first loop, you re-instantiate the $sortOptions variable with the content of the first index of $sortOptions.
#foreach($sortOptions as $index => $sortOption) // <-- $sortOption, not $sortOption(s)
<option value="{{$index}}" {{ (request()->sortBy == $index ? 'selected' : '') }}>
{{ $sortOption["sortDisplay"] }}
</option>
#endforeach

Property [kodeSparepart] does not exist on this collection instance

I want to get all of the data from sparepart database using all() function, then use foreach in view to access the data, but I keep get that error. It works fine when I use the same method for other view blade.
Controller
public function LaporanSisaStok(Request $request) {
if($request->kode == "")
{
$spareparts = Sparepart::all();
return view('laporan/sisaStok')->with(['spareparts' => $spareparts]);
}
else {
$query = DB::table("historisparepart")->select(DB::raw('EXTRACT(MONTH FROM tanggal) AS Bulan, SUM(jumlah) as Sisa'))
->where('kodeSparepart', $request->kode)
->groupBy(DB::raw('EXTRACT(MONTH FROM tanggal)'))
->get();
return view('printPreview/sisaStok', ['data'=>$query]);
}
}
View
<form method="POST" action="{{ route('laporan.sisaStok') }}" enctype="multipart/form-data">
#csrf
<div class="form-group-row">
<label for="sparepart" class="col-sm-2 col-form-label">Sparepart</label>
<select class="custom-select" id="kode" name="kode">
<option value="">-Pilih Sparepart-</option>
foreach($spareparts as $sparepart)
{
<option value="{{$sparepart->kodeSparepart}}"> {{$sparepart->namaSparepart}} </option>
}
</select>
</div>
<br>
<button type="submit" class="btn btn-info"><i class="oi oi-task"></i> Cari </button>
You aren't looping through anything. You need to give the foreach() method a variable from your spareparts collection. I think it might help you avoid confusion, to name the collection variables plural:
In your controller:
$spareparts = Sparepart::all();
return view('laporan/sisaStok', compact('spareparts'));
Then, most importantly, you need to tell foreach what it should produce. In your view, change:
foreach($sparepart)
to
#foreach($spareparts as $sparepart)
Don't forget you are in blade, so use the # before the foreach. Then, assuming you actually have a property on the spareparts model called kodeSparepart, this should work fine.
This is not a looping syntax in the laravel view
foreach($spareparts as $sparepart)
{
<option value="{{$sparepart->kodeSparepart}}"> {{$sparepart->namaSparepart}} </option>
}
It should be like this
#foreach($spareparts as $sparepart)
<option value="{{$sparepart->kodeSparepart}}"> {{$sparepart->namaSparepart}} </option>
#endforeach
And another problem is you are passing the data in wrong way. It should be like this
return view('printPreview/sisaStok', ['spareparts'=>$query]);
You shoud use the plural of your dtb name to loop over the values so your 'sparepart' variable should change to 'spareparts'
$sparepart = Sparepart::all();
return view('laporan/sisaStok')->with(['spareparts' => $sparepart]);
In your view change your loop to the new variable and loop using your current variable, so your view shoul look like this:
View
<div class="form-group-row">
<label for="sparepart" class="col-sm-2 col-form-label">Sparepart</label>
<select class="custom-select" id="kode" name="kode">
<option value="">-Pilih Sparepart-</option>
#foreach($spareparts as $sparepart)
{
<option value="{{$sparepart->kodeSparepart}}"> {{$sparepart->namaSparepart}} </option>
}
#endforeach
</select>
</div>

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

Resources