I am trying to add a user_id array key when doing an eloquent insert. I have the following setup:
View
{!! Form::label('supervisors', 'Assign Supervisor(s)') !!}
{!! Form::select('supervisors[][supervisor_id]', $supervisors, null, ['class' => 'chosen-select', 'multiple']) !!}
User Table
id first_name
12 John
UserSupervisors Table
id user_id supervisor_id
1 12 1
Currently the request $request->get('supervisors') outputs this:
array:1 [▼
0 => array:1 [▼
"supervisor_id" => "1"
]
]
However, I would like it to output this:
array:1 [▼
0 => array:1 [▼
"supervisor_id" => "1",
"user_id" => "12"
]
]
How can I achieve this dynamically?
You can easily use this code to solve the problem:
$user = new User();
$user->user_id = 10;
$user->supervisor_id = Input::get('supervisor_id');
$user->save();
to add an item to the Request $request, you can use merge() like this :
$user_id = 4; //your user id
$request->merge([supervisors => ["user_id" => $user_id]]);
and $request->get('supervisors') will give you the output you need
hope that helps
Related
I'm new in Laravel and I'm trying to merge or join to arrays in one array, which have a one-to-many relationship.
These are the models:
class GroupMenu extends Model
{
public function optionmenu()
{
return $this->hasMany(OptionMenu::class, 'groupmenu_id');
}
}
class OptionMenu extends Model
{
public function groupmenu()
{
return $this->belongsTo(GroupMenu::class, 'groupmenu_id');
}
}
Also I have this function which returns the following arrangement.
public function getOptionMenus()
{
$optionmenu = OptionMenu::whereHas('tipousuario', function ($query) {
$query->where('tipousuario_id', session()->get('tipousuario_id'))->orderBy('orden');
})->get()->toArray();
return $optionmenu;
}
The output is like that:
array:17 [▼
0 => array:2 [▼
"id" => 1
"groupmenu_id" => 1
]
1 => array:2 [▼
"id" => 2
"groupmenu_id" => 1
]
2 => array:2 [▼
"id" => 3
"groupmenu_id" => 1
]
3 => array:2 [▼
"id" => 4
"groupmenu_id" => 2
]
4 => array:2 [▼
"id" => 5
"groupmenu_id" => 2
]
My problem is that I want to have an array where for each groupmenu has within it the array of the optionmenu, something like that:
0 => array:2 [▼
"id" => 1
"optionmenu" => array:3[array of all the optionsmenu that belongs to the groupmenu]
]
1 => array:2 [▼
"id" => 2
"optionmenu" => array:1[array of all the optionsmenu that belongs to the groupmenu]
]
If you want to get all GroupMenu records with related OptionMenu records without any constraint
$data = GroupMenu::with('optionmenu')->get();
However if you want to constrain the related OptionMenu records for each GroupMenu parent record based on the id of tipousuario - which you get from session as shown in your question then you can try something like
$data = GroupMenu::with([
'optionmenu' => fn($query) =>
$query->whereHas('tipousuario', fn($q) =>
$q->where('tipousuario_id', session()->get('tipousuario_id'))->orderBy('orden')
)
])->get();
I have a problem to passing array of arrays from controller to view in Laravel. I've done some research but none of topics helped. My tables are Shops, Items, Items Price. Shops contains shop id, which I get for use from url application/id. In Items Price I got information like shop_id , item_id (these two are FK), price. This table shows which items are in which shops. And in Items I have information about items: id ,picture. When I go to application/1, I want site to show items, which are in this specific shop, information.
My controller method:
public function getItems($id)
{
$items=ItemPrice::where('shop_id', $id)->select('item_id')->get()->toArray();
foreach($items as $item)
$products[] = array(Item::where('id',$item)->get()->toArray());
$shops=Shop::all();
return view('shop')->with(compact(['products','shops']));
}
when I debugging array with dd($products); I get:
array:4 [▼
0 => array:1 [▼
0 => array:1 [▼
0 => array:5 [▼
"id" => 1
"name" => "Item1"
"price" => 0.8
"type" => 2
"img_dir" => "svg/d.jpg"
]
]
]
1 => array:1 [▼
0 => array:1 [▼
0 => array:5 [▼
"id" => 2
"name" => "Item2"
"price" => 1.1
"type" => 2
"img_dir" => "svg/d2.jpg"
]
]
]
2 => array:1 [▼
0 => array:1 [▼
0 => array:5 [▼
"id" => 3
"name" => "Item3"
"price" => 3.1
"type" => 5
"img_dir" => "svg/p1.jpg"
]
]
]
3 => array:1 [▼
0 => array:1 [▼
0 => array:5 [▼
"id" => 4
"name" => "Item4"
"price" => 1.56
"type" => 5
"img_dir" => "svg/p2.jpg"
]
]
]
]
In view I do foreach #foreach($products as $product) and I get error:
Trying to get property 'img_dir' of non-object.
Any help would be appreciated.
Try like this
public function getItems($id)
{
$items = ItemPrice::where('shop_id', $id)
->select('item_id')
->pluck('item_id')
->toArray();
$products = Item::whereIn('id', $items)->get();
$shops = Shop::all();
return view('shop', compact('products','shops'));
}
You have some nested arrays in $products. What you think is a product is in fact an array. Maybe if you simplify your $products variable content :
public function getItems($id) {
$items = ItemPrice::where('shop_id', $id)->select('item_id')->get()->toArray();
$products = [];
foreach($items as $item) {
$products[] = Item::where('id',$item)->get();
}
$shops = Shop::all();
return view('shop')->with(compact(['products', 'shops']));
}
Look at this line
$products[] = array(Item::where('id',$item)->get()->toArray());
$products is an array, and you assign a new element which is an array made by the array value of your query (which contains array).
So you have a 3-level nested array which leads to confusion.
Why don't you just send to your blade view $products = Item::where('id',$item)->get(); ?
in this result:
LengthAwarePaginator {#251 ▼
#total: 2
#lastPage: 1
#items: Collection {#246 ▼
#items: array:2 [▼
0 => ProductCategories {#247 ▼
...
#attributes: array:6 [▼
"id" => 1
"category_name" => "test"
"lang" => "fa"
"images" => "{"images":{"original":"\/uploads\/post_images\/2017\/1512736029.jpeg","300":"\/uploads\/post_images\/2017\/300_1512736029.jpeg","600":"\/uploads\/post_images\/2017\/600_1512736029.jpeg","900":"\/uploads\/post_images\/2017\/900_1512736029.jpeg"},"thumbnail":"\/uploads\/post_images\/2017\/300_1512736029.jpeg"} ◀"
"created_at" => "2017-12-08 10:47:56"
"updated_at" => "2017-12-08 12:27:10"
]
#original: array:6 [▼
"id" => 1
"category_name" => "test test"
"lang" => "fa"
"images" => "{"images":{"original":"\/uploads\/post_images\/2017\/1512736029.jpeg","300":"\/uploads\/post_images\/2017\/300_1512736029.jpeg","600":"\/uploads\/post_images\/2017\/600_1512736029.jpeg","900":"\/uploads\/post_images\/2017\/900_1512736029.jpeg"},"thumbnail":"\/uploads\/post_images\/2017\/300_1512736029.jpeg"} ◀"
"created_at" => "2017-12-08 10:47:56"
"updated_at" => "2017-12-08 12:27:10"
]
...
}
1 => ProductCategories {#248 ▶}
]
}
which i get from this query:
$categories = ProductCategories::paginate(10);
dd($categories);
i'm trying to access to "images" column data such as thumbnail and 300 or etc, when i use foreach this data and show that on table i can't access to them, for example:
{{$categories->images->thumbnail}}
but i get Undefined property error and i can't show that
How about you just cast that field to an array ...
class ProductCategories ...
{
protected $casts = [
'images' => 'array',
];
...
}
#foreach ($categories as $category)
{{ $category->images['thumb'] }}
#endforeach
Laravel 5.5 Docs - Eloquent - Mutators - Array and Json Casting
The variable $categories is a Collection, so you need to get each individual object to get its data. For this you'll need to use a foreach.
#foreach($categories as $category)
{{ $category->images }}
#endforeach
And to have access to thumbnail you'll need to decode the json string that you have in images. For that, you can use json_decode($category->images) function. This will return an array with thumbnail as key.
If you want to make it right, you should keep image related data in a separate table and use a relationship between category and image:
public function images()
{
return $this->hasMany(Image::class);
}
But since you're keeping images data as JSON string, the first thing you want to do is to cast it to array. Add this to the model:
protected $casts = [
'images' => 'array',
];
Then in Blade view:
#foreach ($categories as $category)
{{ $category->images['thumbnail'] }}
#endforeach
Here's my sample code.
$users = 3 users //suppose
$leaders = new Collection();
foreach($users as $user)
{
$name = $user->name;
$username = $user->username;
$leaders->put('name', $name);
$leaders->put('username', $username);
}
dd($leaders);
This gives me the result for only one user (The 3rd user)
Collection {#274 ▼
#items: array:2 [▼
"name" => "user3"
"username" => "username3"
]
}
Because put() is replacing the values with the same keys.
I tried with this too:
$leaders->push($name);
$leaders->push($username);
But I am getting:
Collection {#274 ▼
#items: array:6 [▼
0 => "user1"
1 => "username1"
2 => "user2"
3 => "username2"
4 => "user3"
5 => "username3"
]
}
How to create different item arrays for different users?
Update #1: Got the answer.
Now trying to display the values on the view like this:
#foreach($leaders as $leader)
{{ $leader->username }}
#endforeach
Error: Trying to get property of non-object.
Is this not supposed to work this way for custom collections?
Update #2: Nevermind. Found it.
It is supposed to work this way: {{ $leader['username'] }}
Just try push method
foreach($users as $user)
{
$leaders->push([
'name' => $user->name,
'username' => $user->username,
])
}
I try to populate a multiple select field in laravel like this:
{{ Form::select('maisons[]', $maisons, $partenaire->maisons->pluck('id'), ['class' => '', 'multiple' ]) }}
The option are not select in the dropdown.
I then tried this:
$partenaire->maisons->pluck('id')
and it returns an array: [1,2,3] (example)
I then tried to put the array manually in the field like this:
{{ Form::select('maisons[]', [1,2,3], ['class' => '', 'multiple' ]) }}
The previous line returns the select field with the select iptions.
What is wrong then ?
More information, here is dd($partenaire->maisons->pluck('id'))
Collection {#671 ▼
#items: array:6 [▼
0 => 3
1 => 8
2 => 12
3 => 13
4 => 17
5 => 21
]
}
and dd($maisons)
Collection {#378 ▼
#items: array:300 [▼
1 => "Test 1"
2 => "Test 2"
3 => "Test 3"
4 => "Test 4"
5 => "Test 5"
6 => "Test 6"
...
]
}
From Laravel version 5.3 => ...
pluck()
returns a collection and therefore you need to append toArray() at the end like this:
$partenaire->maisons->pluck('id')->toArray()
and that should return you the options in your select box!