laravel 5.4 form dropdown from database - php

I want to fetch drop down option value & name from database, to do that my controller code is
$roles = Role::pluck('role','user_id');
return view('users.add_role',compact('roles'));
to fetch this data from drop down list my view file code is
<select name="role" class="form-control" >
#foreach($roles as $role)
<option value="{{ $role->user_id }} "> {{ $role->role }} </option>
#endforeach
</select>
but it says error
Trying to get property of non-object (View: C:\xampp\htdocs\auth2\resources\views\users\add_role.blade.php)
if i just only use
<select name="role" class="form-control" >
#foreach($roles as $role)
<option value="{{ $role }} "> {{ $role }} </option>
#endforeach
</select>
then it shows role column of the table, but it not pass option value to database. so what is the correct way to generate option value & name from database?

Your $roles variable containt an array which is looks like
[0] => 'your_role'
[1] => 'your_role'
Where is 0 and 1 index is user_id. So your user_id is set as an index of your $roles array. Simply do it dd($roles) and check the output. $key as $role will work. Where $key will containt the user_id.
#foreach($roles as $key => $role)
<option value="{{ $key }} "> {{ $role }} </option>
#endforeach

I use laravel collective package to generate dropdown list much more easier,
you can do things like, on your blade template and it will render the list for you
{{ Form::select('role', $role )) }}

Related

Old value not setting properly on laravel 9 blade dropdown

In my laravel application I have a simple form with a dropdown.
Dropdown options are getting filled with DB data.
I want to populate my dropdown with user previously selected option on the edit.
Following is what I have done so far..
Blade
<select name="company_id" class="form-control">
#foreach($companies as $company)
#if (old('company_id') == $employee->company_id)
<option value="{{ $company->id }}" selected>{{ $company->name }}</option>
#else
<option value="{{ $company->id }}">{{ $company->name }}</option>
#endif
#endforeach
</select>
Controller.
public function edit(Employee $employee)
{
$companies = Company::all(['id','name']);
return view('employees.edit', compact('employee','companies'));
}
Employee Model
{
use HasFactory, Notifiable;
protected $fillable = [
'first_name', 'last_name', 'email', 'phone', 'company_id'
];
public function company()
{
return $this->belongsTo(Company::class);
}
}
My company table structure
Employee table structure
When I tried with these, it kept showing me the values in the dropdown on the edit but not setting the old value properly.....
Try this as your loop:
#foreach ($companies as $company)
<option value="{{ $company->id }}" {{ $company->id == old('company_id') ? 'selected' : '' }}>
{{ $company->name_en }}</option>
#endforeach
The reason could be typecasting.
#if (old('company_id') === $employee->company_id)
This will never be true. You see old holds string values and you're comparing it against an id which is of type int.
So, this will work for you:
#if ( (int)old('company_id') === $employee->company_id )
Also, there is a new directive you can use instead of conventional if-else statements checked :
#checked( old('key', $employee->key) )
#selected( old('key') === $employee->key )
In Laravel 9 you don't have to use if-else to check the value just use the #selected() blade function/directive.
<select name="company_id" class="form-control">
#foreach($companies as $company)
<option value="{{ $company->id }}" #selected(old('company_id') == $company->id)>{{ $company->name }}</option>
#endforeach
</select>
Also, we have the #checked() function as well:
<input type="checkbox" name="active" value="active" #checked(old('active', $user->active)) />

laravel avoid multiple Select's Option in blade

simply in my controller i have this collections:
$category = Category::with('users')->find($id);
$users = User::with('roles')->get();
and in front end i try to check which users in $users is into $category->users, like with:
in Category model which that belong to User i have one or multiple stored users and i would like checked html option if each $category has user which that is into $user
<select class="form-control multiselect-filtering" multiple="multiple" name="users[]">
#foreach ($category->users as $guser)
#foreach ($users as $user)
<option value="{{$guser->id}}"
#if ($guser->id == $user->id)
selected="selected"
#else
''
#endif
>
{{$user->username}}
</option>
#endforeach
#endforeach
</select>
this code and compare works, but i have multiple <option> which they are maybe selected or not. how can i solve this issue?
You can loop over the collection which is in the $users variable, and use the contains method to check if the current user id in the loop is contained in the $category->users collection.
#foreach ($users as $user)
<option value="{{$user->id}}"
#if ( $category->users ->contains('id', $user->id))
selected="selected"
#endif
>
{{$user->username}}
</option>
#endforeach

Getting data out of array separately in laravel

I'm using shipping system where will calculate shipping price.
this is what i get in my blade currently:
As you see I get id of state and then name of state.
here is my function:
public function index() {
$data = RajaOngkir::Provinsi()->all();
return view('welcome', compact('data'));
}
and this is my blade code:
#foreach($data as $sss)
#foreach($sss as $numbers)
{{ $numbers }} <br>
#endforeach
#endforeach
here is {{$data}} dump info:
what I want is to getting id and name separately so I can use it
in input.
The foreach will loop through anyhow and pull the relevant info. You just then show it within your blade like so:
#foreach ($data as $info)
ID: {{ $info->province_id }} <br />
Name: {{ $info->province }}
#endforeach
Updated:
From my re read you want it as a form drop down select so you can calculate shipping fee's therefore you'd simply do:
<select name="province" id="">
<option value="">Select</option> -> This will be the default select option
#foreach ($data as $info)
<option value="{{ $info->province_id }}">{{ $info->province }}</option>
#endforeach
</select>

Laravel render dropdown list from related table under employee table

I have 2 tables. Employee table and Roles tables. In my employee.show blade I want to render the dropdown list of the role already assgined or available to assign. I am not using collective forms and am a little stuck as all tutorials use thse.
My controller
public function show($employee)
{
$employee = Employees::find($employee);
$roles = Roles::pluck('role_name', 'id');
return view('employees.show')->withEmployee($employee)->withRoles($roles);
}
and my show.blade. Question is how do i pull the complete list from db of all other roles so a user can update?
<div class="form-group">
<label class="col-md-4 control-label" for="roles_id">Role</label>
<div class="col-md-4">
<select id="roles_id" name="roles_id" class="form-control">
<option value="{{ $employee->roles->id }}">{{ $employee->roles->role_name }}</option>
</select>
</div>
</div>
What you've done in your controller seems correct. Your view however should loop through the roles and create options for them. Bear in mind, that you've used Role::pluck('role_name', 'id'), which will return an array of 'id' => 'role_name'.
You can decide which one is selected by adding a selected attribute to the employee's role option by using a ternary statement, which compare's the employee's role_id to the role_id we're currently looking at in the loop.
Try something like this:
<select name="roles_id">
<option value="">Select...</option>
#foreach ($roles as $roleId => $roleName)
<option value="{{ $roleId }}"{!! $employee->role_id == $roleId ? ' selected' : '' !!}>{{ $roleName }}</option>
#endforeach
</select>

Laravel : Form select option value is always NULL when submitting

I have a form where I put de id's of my bands table inside a select option. When I select an id in the dropdownlist and try to submit the form, the value always remains NULL. How can I retrieve the value I selected?
create.blade.php file :
<form>
<select name="band_id">
#foreach ($bands as $band)
<option value="{{ $band->band_id }}">{{ $band->band_id }}</option>
#endforeach
</select>
<input type="submit" value="Submit">
</form>
My Bandcontroller inside my store action :
$bands->band_id = $input['band_id'];
First of all you are using #foreach ($band as $band), make sure it's not a typo and if not then fix it (Could be $bands as $band and assumed you know what I mean). Anyways, you may also try this:
{{ Form::select('band_id', $bands, Input::old('band_id')) }}
Just pass the $bands variable to the View and Laravel will create the SELECT for you, you don't need to loop manually. To retrieve the value, you may try this:
$band_id = Input::get('band_id');
Laravel 6 or above
//blade
{!!Form::open(['action'=>'CategoryController#storecat', 'method'=>'POST']) !!}
<div class="form-group">
<select name="cat" id="cat" class="form-control input-lg">
<option value="">Select App</option>
#foreach ($cats as $cat)
<option value={{$cat->id}}>{{ $cat->title }}</option>
#endforeach
</select>
</div>
<div class="from-group">
{{Form::label('name','Category name:')}}
{{Form::text('name','',['class'=>'form-control', 'placeholder'=>'Category name'])}}
</div>
<br>
{!!Form::submit('Submit', ['class'=>'btn btn-primary'])!!}
{!!Form::close()!!}
// controller
public function storecat(Request $request){
Log::channel('stack')->info('name'.$request->app);
if($request->input('cat')==null){ // retriving option value by the name attribute of select tag
return redirect(route('cats.cat'))->with('error', 'Select an app');
}
$this->validate($request,[
'name'=>'required',
]);
}

Categories