Laravel 5: Sending/saving data from multiple select option - laravel-5

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
}

Related

get many to many values and which of them are selected in laravel

Contacts:
id
name
Tags:
id
name
ContactTags:
contact_id
tag_id
In Contacts model:
public function tags()
{
return $this->belongsToMany(Tags::class, "contacts_tags", "contact_id", "tag_id");
}
So if I do
$contact = Contacts::findOrFail($id);
dd($contact->tags);
I successfully get the tags associated with the contact. But how can I get all tags and a flag indicating which one of those is associated?
I'm trying to prevent fetching all tags, loop them and with each iteration loop all contact_tags and check if tag_id matches. I want to display a list of checkboxes with all tags and check the ones that are in the relation.
This code can help you, but I'm using the SELECT multiple component. You can easily adapt it to use the CHECKBOX component.
Contacts model:
public function tags()
{
return $this->belongsToMany(Tags::class, "contacts_tags", "contact_id", "tag_id");
}
ContactController.php
public function edit(Contact $contact)
{
$tags = Tag::all();
return view('contacts.edit',compact('contact', 'tags'));
}
edit.blade.php
<div class="row">
<div class="col">
<div class="form-group">
<strong>Tags:</strong>
<select name="tags_id[]" multiple>
#foreach ($tags as $tag)
#if( $contact->tags->contains($tag) )
<option value="{{ $tag->id }}" selected>{{ $tag->name }}</option>
#else
<option value="{{ $tag->id }}">{{ $tag->name }}</option>
#endif
#endforeach
</select>
</div>
</div>
</div>
Update in ContactController.php
public function update(Request $request, Post $contact)
{
$validatedData = $request->validate([
'tags_id' => ['array'],
]);
$contact->update($request->all());
$contact->tags()->sync($validatedData['tags_id']);
return redirect()->route('contact.index')->with('success', 'Contact successfully updated!');
}
The validation is just an example. The $validatedData has no use here, but it can be used to update the contact if you validate the other fields.

How to manage in edit items already selected

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

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?

Fetching all users in laravel 5.2

I am trying to fetch all the users in my application so as to pick the user name or id in a select form, but I have not been able to achieve this after a long struggle. My MessageController that retrieves the messages is:
public function getMail(){
$message = Message::orderBy('created_at', 'desc')->get();
$pple = User::where('id', '!=', Auth::id())->pluck('name', 'id')->all();
var_dump($pple);
return view('mail', array('user' => $pple))->with('messages', $message, 'users',$pple );
}
My view that I want to render the users is:
<div>
<select id="recipient">
<option>{{$pple->name}}</option>
</select>
</div>
I have really tried doing this to help me pick up a user id or name to use in my messaging system.I would appreciate if someone helped me with this
You should get your users then pluck to get the result:
$messages = Message::orderBy('created_at', 'desc')->get();
$users = User::where('id', '!=', Auth::id())->pluck('name', 'id');
and return
return view('mail')->with(compact('messages', 'users'));
Then use it this way in your view
<select name="recipient" id="recipient">
#foreach($users as $id => $name)
<option value="{{ $id }}">{{ $name }}</option>
#enforeach
</select>
Don't forget to add a name to your select.
In your view, this should work
#foreach($pple as $userId => $userName)
<option value="{{ $userId }}">{{ $userName }}</option>
#endforeach

Resources