Adding element to an array of arrays - php

I want to call Model::insert() on this array to insert multiple data at once
"person" => array:2 [▼
0 => array:2 [▼
"name" => "Person 1"
"place" => "Place 1"
]
1 => array:2 [▼
"name" => "Person 2"
"place" => "Place 2"
]
]
but the Model excepts a foreign key constraint department_id before it can be inserted into the DB. How do I add department_id to each array inside person array. Is there any other way apart from using for loops to iterate and placing it manually?
Result Array Should look like
"person" => array:2 [▼
0 => array:2 [▼
"department_id" => 1
"name" => "Person 1"
"place" => "Place 1"
]
1 => array:2 [▼
"department_id" => 1
"name" => "Person 2"
"place" => "Place 2"
]
]

Update Person model and "department_id" to the $fillable array:
protected $fillable = [
...
'department_id',
];
Would be something similar to this:
<?php
// app/Models/Person.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Person extends Model
{
use HasFactory;
protected $fillable = [
'name',
'place',
'department_id', // add department_id
];
...
}

I think there is no escaping loop here. You can use array_map here, but it also runs the loop internally.
Person::insert(array_map(function ($person) {
$person['department_id'] = 1;
return $person;
}, $persons));

The solution was similar to the comment by Tim Lewis
$department->people()->insert(...)
but insert didn't seem to assign id automatically
$department->people()->createMany(...)
worked
Thank you

Related

lumen/laravel pluck not working in with relationship

I have pivot table vacancy_tag. I tried different options (value,select, lists and etc), but didn't go further than that. My request:
Vacancy::where('id',1)->with(['tags' => function ($q){
$q->select('tags.id')->pluck('id');
}])->get()->toArray();
return this:
"id" => 1,
"title" => "pm",
"tags" => array:2 [▼
0 => array:1 [▼
"id" => 1
]
1 => array:1 [▼
"id" => 2
]
but need this:
"id" => 1,
"title" => "pm",
"tags" => [
1,
2
]
I would like to receive the data result in a query, without using a methods transformation of the collection, if possible.
PS: I slightly corrected the example, need to display all fields of the vacancy + an array of tags.

Merge arrays on Laravel

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

Passing array of arrays to blade

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(); ?

Get only some fields from array in Laravel requests

In input I have such an array:
array:1 [
"prizes" => array:1 [
1 => array:2 [
"prize_id" => "1"
"priority" => "1"
"some_fields" => "some_value"
]
]
]
In controller, I try to get only two fields:
$request->only([
'prizes.*.priority',
'prizes.*.prize_id'
]);
but i should get this:
array:1 [
"prizes" => array:1 [
"*" => array:2 [
"priority" => array:1 [
0 => "1"
]
"prize_id" => array:1 [
0 => "1"
]
]
]
]
How to get array with needed fields?
You are getting an array as the result because you are using .*. which is saying get ALL priorities for the prizes, which is why it is returning an array instead.
If you use the dot notation, you will access the only priority for the prize.
Like so:
prizes.priority
If you would like to validate for EVERY prize that you get coming in, you will use *. before hand to access each array, like so:
*.prizes.priority
Edit: bit more information here https://laravel.com/docs/master/validation#validating-arrays

PHP Laravel Foreach trough multi array

I have the following multi dimension array and I am not able to do a foreach loop (with laravel). I want to show the name.
Any idea how to loop trough that array to show just the name? I reduced the showed array -> ...
I want to loop trough that array not in a view but in a controller because i want to create a database entry for every client
array:1 [▼
"client" => array:52 [▼
0 => array:11 [▼
"name" => "Company One"
...
]
1 => array:11 [▼
"name" => "Company 2"
...
]
Thanks for your help.
$array = [
'client' => [
[
'name' => 'Company One',
'foo' => 'Foo One',
],[
'name' => 'Company 2',
'foo' => 'Foo 2',
]
]
];
$names = array_pluck($array['client'], 'name');
foreach($names as $name) {
echo $name; // Replace this with the logic to create DB entry
}
Its easy all you have to do is this ,lets assume that your array are in the varibale $myArray
$myArray = [▼
"client" => array:52 [▼
0 => array:11 [▼
"name" => "Company One"
...
]
1 => array:11 [▼
"name" => "Company 2"
...
]
then you have to do:
#foreach ($myArray->client as $data)
{{$data->name}}
#endforeach

Categories