Convert collection of models into an array with id as key - php

I am using Laravel HTML component to create a dropdown to list all the groups to which an user can belong.
The list of groups comes from a Groups table.
Currently in my controller my code looks like
$groups = array();
$groupModels = Group::all(['id', 'name']);
foreach ($groupModels as $groupModel) {
$groups[$groupModel->id] = $groupModel->name;
}
return view('myview', compact('groups'));
and in my view I have the following code to create the dropdown
{!! Form::select('group', $groups, null, ['class' => 'form-control']) !!}
This works, but I am trying to see if there is a way to avoid the foreach loop and directly convert the list of Models into an array. Is it possible?

Use pluck() method:
$groups = Group::pluck('name', 'id');
return view('myview', compact('groups'));

Related

Form select box {!!Form::select()!!} Laravel

I'm using Laravel Collective Form builder in my view and i'm populating this select box from a table in my DB like this
I am having an issue with my values not matching up and my dropdown is also giving me the values as an array...
Here's what I have in my PostsController:-
public function edit(Post $post)
{
$categories = Category::all()->pluck('title', 'id')->toArray();
return view('posts.edit')->withPost($post)->withCategories($categories);
}
and here's my view edit.blade.php:-
{{ Form::label('category_id', 'Category :')}}
{!! Form::select('category_id', $categories, null, ['class' => 'form-control']) !!}
So I need little help?
Here's the value issue I was talking about:
enter image description here
Here's the array issue I was talking about:
enter image description here
no need to use toArray() pluck method automatically create an array.
try this
$categories = Category::pluck('title', 'id');
First of all your code seems like not proper.
$categories = Category::all()->pluck('title', 'id')->toArray();
should be
$categories = Category::pluck('title', 'id')->toArray();
Firstly update you controller function. I think that will help:-
public function edit(Post $post)
{
$categories = Category::pluck('title', 'id')->toArray();
return view('posts.edit', [
'post' => $post,
'categories' => $categories
]);
}
Try this code and let me know need help.

Fill laravel select with eloquent model using pluck

I'm trying to fill a laravel (version 5.5) select with data from the eloquent model.
So I'm geting data like this:
$types = Type::pluck('name', 'id');
And returning to the view:
return view('something')->with('types', $types->all());
So here is my view select:
{{ Form::select('type', $types, NULL, ['id' => 'myselect', 'class' => 'form-control']) }}
Well, the problem is: each option is an object, like this:
{"id":1,"name":"test","created_at":"2017-12-29 18:09:45","updated_at":"2017-12-29 18:09:45"}
And what I want is: the value equal to the id and the name equal to the name
How can I do this?
Change this:
return view('something')->with('types', $types->all());
To:
return view('something')->with('types', $types);
try this :
$types = Type::pluck('name', 'id')->toArray();
return view('something', compact('types'));

Binding pivot table with Laravel Form Builders using checkbox group

I'd like to bind my checkbox group Form::checkbox('services[]') with data from my pivot table but I'm having trouble doing so, I think this is because no key is being returned with service_id.
My data model is as follows:
Business
Service
Business_Service table to store many to many link.
Blade Template
#foreach($service as $service)
{!! Form::checkbox('services[]', $service->id, (in_array($service->id, $selected_services) ? true : false)) !!}
#endforeach
Controller
$service = Service::all();
$selected_services = Auth::user()->business->services()->get();
return view('signup.step2', compact('service', 'selected_services'));
When I return $selected_services I can see the following:
[{"id":2,"name":"Service
1","image":"picture.png","created_at":"2017-03-31
00:31:20","updated_at":"2017-03-31
00:31:20","pivot":{"business_id":103,"service_id":2}},{"id":3,"name":"Service
2","image":"picture.png","created_at":"2017-03-31
00:31:23","updated_at":"2017-03-31
00:31:23","pivot":{"business_id":103,"service_id":3}}]
I have tried changing $selected_services like this:
$selected_services = Auth::user()->business->services()->keyBy('service_id');
But this only returns one row and doesn't associate a key to the row as expected.
If you want to use inbuilt Laravel functions, then you could use the Collection::pluck function.
$businessServices = Auth::user()->business->services->pluck('id');
I can prepare another array instead of using the collection Eloquent returns but I was hoping there was some built-in function by Laravel I could use.
$service = Service::all();
$business_services = Auth::user()->business->services()->get();
$selected_services = [];
foreach ($business_services as $ss) {
$selected_services[] = $ss->pivot->service_id;
}
return view('signup.step2', compact('service', 'selected_services'));

Dropdown menu with eloquent

I have a form and I want to give user ability to choose user in a drop down, but when I return the data it gives me an object, How can I make a drop down select for each user in array.
This is my code
view
{!! Form::select('users', array($users),null, ['placeholder' => 'Pick a user']) !!}
controller
$users = User::lists('name');
return view('view')->with('users', $users);
now it returns
Placeholder
["user1", "user2"]
You need to add ID to the list to make it work:
$users = User::pluck('name', 'id');
Also, use pluck() instead of lists() because lists() is depricated.

Laravel PHP: Display array elements in drop down list alphabetically without using sort()

I have a Laravel PHP Photo Gallery application that allows the user to create an album and then insert photos into an album of their choice from a drop down list. This requires the user to create the album first since the drop down list is dynamic based on which albums actually exist. The drop down list is currently functioning properly but it does not display albums (array elements) alphabetically.
I've tried using the 'sort()' method but the problem is that the array element ids then become switched/re-sorted when doing so. I do not want the array ids to be re-sorted since this will put photos into the wrong albums.
So I want to know if there is a way to display the albums alphabetically in a drop down list while not re-sorting their array element ids.
Controller:
public function create()
{
$stoneArray = $this->stone->all()->toArray();
if (empty($stoneArray)) {
$dropdown[0] = 'There are no stones';
}
foreach ($stoneArray as $stone) {
$dropdown[$stone['stone_id']] = $stone['stone_name'];
// sort($dropdown); /* This re-sorted the array element ids */
}
$data = array('type' => 'stone_photo', 'dropdown' => $dropdown);
$this->layout->content = \View::make('forms.stones.new-photo', $data);
}
View:
<div class="form-group">
{{ Form::label('stone_id', 'Stone: ') }}
{{ Form::select('stone_id', $dropdown, array('class' => 'form-control')) }}
</div>
Any help is greatly appreciated! Thank you!
EDIT
I'm making some assumptions here about your file structure, but it should give you the idea.
In: app\Acme\repositories\Eloquent\EloquentStoneRepository.php or whatever you called it, there's a function:
public function all()
{
return Stone::all();
}
(I think that's what it looks like, but I'm not positive). Try changing that to:
public function all()
{
return Stone::orderBy('column_name', 'asc')->get();
}
If you use all() somewhere else and don't want it sorted, consider adding another function:
public function all_sorted()
{
return Stone::orderBy('column_name', 'asc')->get();
}
Hope that helps!
Edit:
Changed ->all() to ->get() so eloquent can properly sort it.

Categories