laravel Insert two array into the database - php

Hey guys I have to Arrays named $keys and $values Like this
keys
array:2 [▼
0 => "1"
1 => "2"
]
values
array:2 [▼
0 => "US"
1 => "Canada"
]
And I want to insert them to the database with my controller :
$keys = $request->key;
$values = $request->value;
$datas = new Collection();
$datas->key_id = $keys;
$datas->value = $values;
$datas->product_id = $product_id;
ProductSearchValuesModel::create($datas);
But this way is not working
What is wrong with my code?

It's better to change those array to jSon format. Please! check this code.
$datas = new Collection();
$datas->key_id = json_encode($keys);
$datas->value = json_encode($values);
$datas->product_id = $product_id;
ProductSearchValuesModel::create($datas);
You'll have to use json_decode($array, 1) whenever you want to pull from database and use them. Also please check field length of that table ProductSearchValues to make sure it can hold that data.
Thanks

Related

elements in array is not working with in_array

number 3 should be in array $songsid but when i used in_array method output was null
nuder my function is dd($songsid)
public function index()
{
$songs = Song::latest()->paginate(20);
$songid = Collection::select("song_id")->where("user_id", "=", auth::user()->id)->get();
$songsid = $songid->toArray();
// dd($songsid);
if(in_array(3, $songsid))
{
dd("yes");
}
else
{
dd("no");
}
}
output of $songsid array dd($songsid)
array:2 [▼
0 => array:1 [▼
"song_id" => 3
]
1 => array:1 [▼
"song_id" => 2
]
]
$songsid is not an array of scalar values, but an array of arrays.
You could use array_column() to extract IDs from the array,
in_array(3, array_column($songsid, 'song_id')
Unless you really need to convert to array, you could use collection methods to check that out.
$songid = Collection::select("song_id")->where("user_id", "=", auth::user()->id)->get();
if ($songId->contains('song_id', 3)) ...
In your in_array method, you need an indexed array, ex : $songsid = [3,2]; You can use pluck method :
$songsid = $songid->pluck('id')->toArray();
if(in_array(3, $songsid))
{
dd("yes");
} else {
dd("no");
}
in_array() searches in the array values, that is not nesting.
You may want to use array_culumn() like
in_array(3, array_column($songsid, 'song_id')
or search for ['song_id' => 3] like
in_array(3, array_column($songsid, ['song_id' => 3])

How to array merge in laravel

I have a problem here, I want to combine 2 arrays into 1, I've tried using array_merge from php, and merge () from laravel but nothing works
//$plucked is EAV database
$vendor = Vendor::find($id)->toArray();
$vendor_detail = Vendor_detail::where('vendor_id',$id)->get();
$plucked = $vendor_detail->pluck('vendor_name','vendor_value');
$merged = array_merge($plucked, $vendor);
// $merged = $vendor->merge($plucked)->all();
dd($merged);
I think because the array is different, there array $plucked
#items: array:10 [▼
"user_email" => "cobaupdatelagi#gmail.com"
]
and there my array in $vendor
array:15 [▼
"vendor_id" => 39
"province" => "ACEH"
]
the output that I want
$somearray =[
"vendor_id" => 39
"province" => "ACEH"
"user_email" => "cobaupdatelagi#gmail.com"
]
Your $vendor is one associative array while $plucked is an array of arrays. Even if it has only one item it will be of index zero so you need to loop through $plucked and merge for each one.
$vendor = Vendor::find($id)->toArray();
$vendor_detail = Vendor_detail::where('vendor_id',$id)->get();
$plucked = $vendor_detail->pluck('vendor_name','vendor_value');
$merged = [];
foreach($plucked as $p){
$merged[] = array_merge($p, $vendor);
}
dd($merged);
$vendor = Vendor::find($id);
$vendor_detail = Vendor_detail::select('vendor_id','province')->where('vendor_id',$id)->get()->toArray();
$data= array_merge($vendor,$vendor_detail);
I think you should use database join to get faster results.
$vendor = Vendor::join('vendor_details', 'vendors.id', '=', 'vendor_details.vendor_id')
->select('vendors.*', 'vendor_name','vendor_value')
->where('id', $id)
->first();
if ($vendor) {
$vendor = $vendor->toArray();
}
$vendor_detail = Vendor_detail::where('vendor_id',$id)->get(); will give you a collection
as well as $plucked = $vendor_detail->pluck('vendor_name','vendor_value'); will give you a collection, so, either you can use collection merge or you may like to loop through one and add merge another as other answer is doing, but these are not array, you are getting collections.

Laravel 5.4 save json to database

help me with save json to db. Table field type - text.
I have Model with cast array
class Salesteam extends Model
{
protected $casts = [
'team_members' => 'array'
];
}
I want get json like this {"index":"userId"} and store it to db.
Example:
{"1":"7","2":"14","3":"25","4":"11"}
I have Salesteam Model and 'team_members' column in db to saving all user id's belong to this team.
My code find team by id, get all 'team_members' attribute and add new user to this team. I want store all users in json format and incrementing index when add new user id.
Salesteam attributes:
"id" => 20
"salesteam" => "Admin"
"team_leader" => 0
"invoice_target" => 884.0
"invoice_forecast" => 235.0
"team_members" => "[1,66,71]"
"leads" => 0
"quotations" => 0
"opportunities" => 0
"notes" => ""
"user_id" => 1
"created_at" => "2017-09-22 09:13:33"
"updated_at" => "2017-09-22 13:10:25"
"deleted_at" => null
Code to add new user to team:
$salesTeam = $this->model->find($salesTeamId);
$teamMembers = $salesTeam->team_members;
$teamMembers[] = $userId;
$salesTeam->team_members = $teamMembers;
$salesTeam->save();
But it stores to db array and without index
"team_members" => "[1,34,56]"
From Laravel documentation - Array & JSON Casting "array will automatically be serialized back into JSON for storage"
Where i'm wrong?
To make a json string like this
{"1":"7","2":"14","3":"25","4":"11"}
In php, you must pass a key, when you're pushing elements to array. e.g.
$teamMembers = [];
$teamMembers['1'] = 7;
$teamMembers['2'] = 14;
...
If you don't make it an associative array, php will consider it as json array when converting to json string..
Tip: You may pass only one key and it will work too.
e.g.
$test = [1, 2, 3, 4, 5, 6];
$test['10'] = 56;
echo json_encode($test);
Output:
"{"0":1,"1":2,"2":3,"3":4,"4":5,"5":6,"10":56}"
PHP-Reference
Simply use
$teamMembers = json_encode($salesTeam->team_members);
That should do be all.
if you get this "[1,34,56]" just do json_decode($team_members)
and you will have this:
array:3 [▼
0 => 1
1 => 34
2 => 56
]
Simple Solution
$books = App\Book::all();
$user->books = $books->toJson();
$user->save(); //example: userid -> 2
$user = App\User::find(2);
$userBooks = json_decode($user->books, true); // to generate object again

recursive php function: trouble spotting the bug

I have a family tree app in laravel, and I want to be able to show an outline view (start with a family from long ago, show its kids, show those kids' families, those families' kids, etc).
So I made this recursive get_descendants function:
public static function get_descendants(Family $family, $results_array, $counter)
{
// start new round with a different temp array, to keep track
$counter++;
$this_array = "array_$counter";
$$this_array = [];
array_push ($$this_array, $family->caption);
$kids = FamilyController::get_kids_of_family($family);
// if family has no kids, return 0;
if (!count($kids))
{
return 0;
}
else // add kids and check for their families
{
foreach ($kids as $kid) {
array_push ($$this_array, $kid->firstname);
// get families made by kid- for each one, call get_descendants
$families_made = FamilyController::get_families_person_made($kid);
foreach ($families_made as $new_family) {
array_push($$this_array, self::get_descendants($new_family, $$this_array, $counter));
}
};
// we've gone through the kids, add this round's array to the general results array
array_push ($results_array, $$this_array);
}
return $results_array;
}
I've confirmed with print statements that the looping through is correct, but there's a problem with the way I'm saving the results. I want to get something like this, where the top family shows once, with children and their families nested:
array:1 [▼
0 => array:4 [▼
0 => "Padme & Anakin"
1 => "Leia"
2 => array:3 [▼
0 => "Leia & Han"
1 => "Kylo Ren"
]
3 => "Luke"
]
]
but I'm getting this (with an extra repeat in the middle):
array:1 [▼
0 => array:4 [▼
0 => "Padme & Anakin"
1 => "Leia"
2 => array:3 [▼
0 => "Padme & Anakin"
1 => "Leia"
2 => array:3 [▼
0 => "Leia & Han"
1 => "Kylo Ren"
]
]
3 => "Luke"
]
]
Can anyone see where my mistake is?
Update: it turns out that it works if I get rid of that final results_array and just use the dynamic one the whole way, like this:
public static function get_descendants(Family $family, $results_array, $counter)
{
// start new round with a different temp array, to keep track
$counter++;
$this_array = "array_$counter";
$$this_array = [];
array_push ($$this_array, $family->caption);
$kids = FamilyController::get_kids_of_family($family);
// if family has no kids, return 0;
if (!count($kids))
{
return 0;
}
else // add kids and check for their families
{
foreach ($kids as $kid) {
array_push ($$this_array, $kid->first);
// get families made by kid- for each one, call get_descendants
$families_made = FamilyController::get_families_person_made($kid);
if (count($families_made))
{
foreach ($families_made as $new_family) {
array_push($$this_array, self::get_descendants($new_family, $$this_array, $counter));
}
}
};
}
return $$this_array;
}
Looks unnecessarily complex, with dynamic arrays, and you keep populating the same array, so that's why Luke appears in the wrong place.
A cleaner solution might be to be very specific about where people are in the array rather than using a dynamic array name. Just a suggestion -
public static function getDescendants(Family $family)
{
$family = [];
$family['name'] = $family->caption;
if ($kids = static::getKidsOfFamily($family)) {
foreach ($kids as $kid) {
$family['children'][] = $kid->firstname;
$subfamilies = static::getFamiliesPersonMade($kid);
foreach ($subfamilies as $subfamily) {
$family['subfamilies'][] = static::getDescendants($subfamily);
}
};
}
return $family;
}
would produce something like
array [
"name" => "Padme & Anakin"
"children" => array [
"Leia",
"Luke"
],
"subfamilies" => array [
array [
"name" => "Leia & Han"
"children" => array [
"Kylo Re"
]
]
]
]

PHP array loop and format

I am very new to PHP, learning fast but not fast enough! I am also learning Laravel 5.1.
I am trying to build a HTML select list array from an Eloquent query output, in the correct format for form builder (Form::select).
I have the following call to Eloquent to pull the data:
// Get list of States for address select
$states = State::all()->toArray();
It returns the following array:
array:8 [▼
0 => array:2 [▼
"id" => "1"
"state" => "ACT"
]
1 => array:2 [▼
"id" => "2"
"state" => "NSW"
]
...
];
I want to loop through it and generate the following output:
array = [
'' => 'State', <-- This is the default for the select list
'1' => 'ACT',
'2' => 'NSW',
...
];
I am using Laravel 5.1, so I am using the included array_add() function in my helper.
I call my function like this:
$states = create_select_list($states, 'State');
I next want to format the output so it is ready for the Form::select statement. I have tried the code below (as the final try from a few iterations!) but unsuccessfully.
function create_select_list($data, $default)
{
// Declare array and set up default select item
$container = ['' => $default];
// Loop through data entries and build select list array
foreach($data as list($entry, list($key, $value))) {
$container = array_add($container, $key, $value);
}
// Return the select list array
return $container;
}
All help or suggestions are appreciated!
This answer is not about loop fix. I think previous comment should help you.
Just another idea. You can try use array_map instead foreach for this case.
For example:
$states = ['' => 'State'];
array_map(function($item) use (&$states) {
$states[$item['id']] = $item['state'];
}, State::all()->toArray());
Loop like below:
foreach($data as $key => $keyArr ) {
$container = array_add($container, $keyArr['id'], $keyArr['state']);
}
You don't need to use list() in your foreach loop, instead try:
foreach($data as $key => $value) {
$container = array_add($container, $key, $value);
}
The PHP documentation gives a good overview of what list() actually does.

Categories