How to manage in edit items already selected - laravel

I have a select2, which lists all items of a database table. One of these items is already selected. In edit mode, how can I show the already selected item and list the rest of the items?
IN CONTROLLER:
$offertaheader = Offertaheader::find($id_offertaheader);
$clients = Client::all()->where('visibility',1)
->sortBy('nome');
return view('offertas.edit',compact('offertaheader','clients'));
IN VIEW BLADE:
<select class="form-control select2" name="id_cliente" style="width: 100%">
<optgroup label="<?php echo htmlentities(utf8_encode('CLIENTE'), 0, "UTF-8"); ?>">
<option></option>
#foreach($clients as $client)
<option value="{{$client->id}}" {{ (old('id_client', $client->id) == ($client ? $client->id : '') ? ' selected' : '') }}>{{$client->nome}}</option>
#endforeach
</select>
I want that the already selected item must be shown and at the same time the user can change it in the blade. I prefer to avoid front-end codings like jquery or ajax.

You can update using sync method, sth like this,
public function upate()
{
$todo = Todo::findOrFail($id);
$data = $request->all();
$todo->update($data);
$users = $request->users;
$users = User::find($users);
$todo->users()->sync($users);
return response()->json("success",200);
}

Related

How to build conditional list of dropdown options in Laravel Voyager

I have a problem with Laravel Voyager v1.2. I need to filter list of related list of options in select dropdown easily by where condition. So let's say I have Post with relation to Category, but I don't want to list all Categories in select dropdown, but just that active ones.
I tried to force Voyager to take my own method to build an relationship in Post model:
public function category_id() {
return $this->belongsTo('Post::class')->where('active',1);
}
Also tried to define scope in BREAD JSON options for the category field:
{
"relationship": {
"key": "id",
"label": "name",
"scopes": [
"active"
]
}
}
Post Model part:
public function scopeActive($query) {
return $query->where('active', 1);
}
This is how my Post class look like (I don't actualy need to filter active categories, but food categories by it's IDs):
public function soup1() {
return $this->belongsTo('App\Meal')->where('meal_category_id',1);
}
public function soup2() {
return $this->belongsTo('App\Meal')->where('meal_category_id',1);
}
public function mealy() {
return $this->belongsTo('App\Meal')->where('meal_category_id',7);
}
public function scopeSoups($query)
{
return $query->where('meal_category_id', 1);
}
public function scopeMealy($query)
{
return $query->where('meal_category_id', 7);
}
I want to receive filtered list of options instead of all model rows.
You can do this easily by overriding the blades in voyager:
Step 1 :
Copy relationship.blade.php
from: /"YourProject"/vendor/tcg/voyager/resources/views/formfields/relationship.blade.php
To: /"YourProject"/resources/views/vendor/voyager/formfields/relationship.blade.php
This way voyager will use this file in your your project views instead of the package file in the vendor.
Read More: Voyager Documentations
Step 2 :
In the line 25 of relationship.blade.php you'll see this block of code:
<select
class="form-control select2-ajax" name="{{ $options->column }}"
data-get-items-route="{{route('voyager.' . $dataType->slug.'.relation')}}"
data-get-items-field="{{$row->field}}"
>
#php
$model = app($options->model);
$query = $model::where($options->key, $dataTypeContent->{$options->column})->get();
#endphp
#if(!$row->required)
<option value="">{{__('voyager::generic.none')}}</option>
#endif
#foreach($query as $relationshipData)
<option value="{{ $relationshipData->{$options->key} }}" #if($dataTypeContent->{$options->column} == $relationshipData->{$options->key}){{ 'selected="selected"' }}#endif>{{ $relationshipData->{$options->label} }}</option>
#endforeach
</select>
Which you should override it with this:
#if($options->table == 'categories')
<div class="ap-form-input">
#php
$model = app($options->model);
$query = $model::where('active', true)->get();
#endphp
<select class="form-control select2" id="language-select" name="{{ $options->column }}">
#if(!$row->required)
<option value="">{{__('voyager::generic.none')}}</option>
#endif
#foreach($query as $relationshipData)
<option value={{ $relationshipData->{$options->key} }} #if($dataTypeContent->{$options->column} == $relationshipData->{$options->key}){{ 'selected="selected"' }}#endif>{{ $relationshipData->{$options->label} }}</option>
#endforeach
</select>
</div>
#else
<div class="ap-form-input">
<select class="form-control select2" name="{{ $options->column }}">
#php
$model = app($options->model);
$query = $model::all();
#endphp
#if(!$row->required)
<option value="">{{__('voyager::generic.none')}}</option>
#endif
#foreach($query as $relationshipData)
<option value={{ $relationshipData->{$options->key} }} #if($dataTypeContent->{$options->column} == $relationshipData->{$options->key}){{ 'selected="selected"' }}#endif>{{ $relationshipData->{$options->label} }}</option>
#endforeach
</select>
</div>
#endif
This way when you're using categories relationship you will only get the active categories.
Click on the link and follow these simple steps, just now I solved my issue.
https://voyager.readme.io/docs/relationships

How to show old data of select element

I am stuck for 2 days, do you know how to show old data of select element in Laravel?
<select name="sexe" id="sexe" class="form-control">
<option value="">Choice</option>
<option>Women</option>
<option>Man</option>
</select>
I have tried this but without success:
<select class="form-control" name="sexe">
<option value="male" #if (old('sexe') == 'male') selected="selected" #endif>male</option>
<option value="female" #if (old('sexe') == 'female') selected="selected" #endif>female</option>
</select>
My Controller
public function edit($id)
{
//
$candidats = Candidat::find($id);
$permis = Permis::all();
return view('admin.candidats.edit', compact('candidats', 'permis'));
}
public function update(Request $request, $id)
{
$request->validate([
'sexe' => 'required|string',
'fk_permis' => 'required'
]);
$candidats = Candidat::find($id);
$candidats->sexe = $request->get('sexe');
$candidats->fk_permis = $request->get('fk_permis');
$candidats->save();
return redirect()->route('candidats.index')
->with('success', 'mise à jour effectuée');
}
Edit:
1) index.blade.php
2) edit.blade.php
In your update function put withInput():
return redirect()->route('candidats.index')
->with('success', 'mise à jour effectuée')->withInput();
In your select you can do this:
<select class="form-control" name="sexe">
<option value="male" #if (old('sexe') == 'male') selected="selected" #elseif($candidats->sexe == 'male') selected="selected"
#endif>male</option>
<option value="female" #if (old('sexe') == 'female') selected="selected" #elseif($candidats->sexe == 'female') selected="selected"
#endif>female</option>
</select>
I loaded the selected option from your model here
#elseif($candidats->sexe == 'male') selected="selected"
So, if you saved 'male' in your sexe attribute this option will be selected.
Take a look here for more info:
If the old data was stored as a model, which I assume it was since this is a Laravel question and not a javascript question, you can use form-model binding to easily load the old data the next time you go to the page.
So, when you open your form, bind the model:
{{ Form::model($yourModel, array('route' => array('yourModel.update', $yourModel->id))) }}
And then within the select method, laravel (collective) can automatically make the old data the selected value. Using the Laravel helper it might look like this:
{!! Form::select('sexe', $listOfYourNameAndIdForYourSelectItem, null, ['class'=>'form-control', 'id'=>'sexe']) !!}
By making the third argument null, as above, Laravel will make the model's old data the selected element.
Check the docs on the Laravel forms package for more info.

Get data Based On Selected Value in Drop Down menu - Laravel 5.4

I have two tables posts and category.
My controller:
public function index()
{
$posts = Post::orderBy('id', 'desc')->get(['category']);
$data = DB::table('posts')->paginate(5);
$category = DB::table('category')->pluck('cname','id');
return view('posts.index', [
'posts' => $posts,
'category'=> $category,
'posts' => $data
]);
}
My blade:
<select class="form-control" name="category" id="category_add">
<option value="">Select Category</option>
#foreach($category as $key=>$value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
Now my code shows a drop down data from the database...
What I need is: When I select the drop down category it should only shows the particular category of data in the view dynamically
Any one help
Did you mean after selecting a category from the dropdown there will be another section which will show data about that specific category?
One way to do it is through ajax request. I dont know if i got your question right or wrong. can u explain a bit if i got it wrong?

Laravel: needing help querying two tables into one result

Im interested in giving users the option to add articles to custom lists that they create. (like youtube's playlist feature).
I want to know how to show a 'checked' checkbox next to a list if the article already exists within it, so they don't add it twice.
My database tables:
list : | id | person_id | list_name | list_desc
list_ref : | id | list_id | article_id
My code for displaying lists.
$lists = Lists::where('person_id', Auth::user()->person_id)->get();
#foreach($lists as $list)
<input type="checkbox" id="available_list" value="{{ $list->id }}">
{{ $list->list_name }}
#endforeach
If anyone could help me understand the code to query the two tables to see if list already used || list is available.
You could use a raw expression in conjunction with a left join like this:
$lists = DB::table('list')->
leftJoin('list_ref', 'list_ref.list_id', '=', 'list.id')->
select(DB::raw('list.*, IF(list_ref.list_id = list.id, 1, 0) used'))->
where('person_id', Auth::user()->person_id)->
get();
The above uses a join to figure out which list rows has a corresponding key in the list_ref table. The result will contain a field called used that will tell if the entry has a reference in the list_ref table.
You should now be able to generate you form like this:
#foreach($lists as $list)
<input type="checkbox" id="available_list" value="{{ $list->id }}" {{ $list->used ? "CHECKED" : "" }}>
{{ $list->list_name }}
#endforeach
First crate class, here is example for facility
class HotelFacilities
{
public $facility_id;
public $facility;
public $status;
}
Get all data
$facilities = Facility::all();
Get user related data
$user_facilities = UserFacility::where('user_id', 3)->get();
//Here you add status
$array_hotel_facility = array();
for($i=0; $i<count($facilities); $i++)
{
$obj_hotel_facilities = new HotelFacilities;
$obj_hotel_facilities->facility_id = $facilities[$i]['id'];
$obj_hotel_facilities->facility = $facilities[$i]['facility'];
$obj_hotel_facilities->status = false;
for($j=0; $j<count($user_facilities); $j++)
{
if($user_facilities[$j]->facility_id == $facilities[$i]->id)
{
$obj_hotel_facilities->status = true;
}
}
//Pass this array to view
$array_hotel_facility[$i] = $obj_hotel_facilities;
}
//Pass to view
return view('extranet.view_facilities')->with('facilities', $array_hotel_facility);
//Generate UI like this
#foreach($facilities as $facility)
<div class="form-group col-md-3">
<div class="form-group">
<label>
<input type="checkbox" class="minimal" name="facilities[]" value="{{ $facility->facility_id }}" <?php if($facility->status){echo "checked";} ?>>
{{ $facility->facility }}
</label>
</div>
</div>
#endforeach

Laravel 5: Sending/saving data from multiple select option

I'm having trouble to get all data (options) selected in multiple select dropdown. Here is the blade code:
<div class="form-group">
<select name="roles[]" class="form-control select2 select2-hidden-accessible" multiple="" data-placeholder="User roles" style="width: 100%;" tabindex="-1" aria-hidden="true">
#foreach ($roles as $role)
<option value="{{$role->name}}">{{$role->display_name}}</option>
#endforeach
</select>
</div>
That's how I get all "roles" listed, I have like seven of them in database and one should be able to select as much as one wants.
Here is the part in the controller:
$input = Input::all();
$roles[] = $input["roles"];
foreach ($roles as $role) {
echo $role; //this is just for testing purposes
}
But, only last one in that array is being showed. So if I select "admin, moderator, subscriber" it will only show "subscriber". Please help me, it's obvious I'm missing some small detail.
I'm sorry I can't test this answer right now. Try:
$roles = Input::get('roles');
foreach ($roles as $role) {
echo $role; //this is just for testing purposes
}
So the problem was double array I had both name of the select tag and var in the controller with "[]" indicating they are array, removing "[]" from $roles[] in controller solved it.
In case anyone needs this:
$input = Input::all();
$roles = $input["roles"]; // removed brackets
foreach ($roles as $role) {
echo $role; // this is just for testing purposes
}

Resources