Array to string conversion laravel 5.5 when seeding data - php

Array to string conversion
(SQL)
`insert into `group_members` (`id`, `group_id`, `alias`) values (1, 20, Lilian Marvin PhD)`
$users = User::where('role_id','=',3)->select('id','display_name')->get();
foreach ($users as $user) {
$groups = Group::select('id')->get()->toArray();
// echo $user->display_name ." " .$user->id ."<br/>";
DB::table('group_members')->insert([
'id' => $user->id,
'group_id' => array_random($groups),
'alias' => $user->display_name
]);
}
in the array_random, I believe there's an error

You are trying to save array in group_id column. You need to save only id not array
try this
DB::table('group_members')->insert([
'id' => $user->id,
'group_id' => array_random($groups)['id'],
'alias' => $user->display_name
]);

If you want to get any one of the group then you can try
array_random($groups, 1),
if you want to store multiple, then you may like to convert it to json
json_encode(array_random($groups, 1)),

used laravel helper method Arr::random
The Arr::random method returns a random value from an array
use Illuminate\Support\Arr;
$array = [1, 2, 3, 4, 5];
$random = Arr::random($array);
// 2 - (retrieved randomly)

Related

Bulk insert or update for the given where

I have a function that gets $homes and $member_id as parameters. $homes is an array, $member_id is an integer.
$homes = array( 'home13', 'home21', 'home34', 'home44' );
$member_id = 5;
How do I insert/update into the following DB?
in the format:
id home_name member_id
1 home13 5
2 home21 5
2 home34 5
2 home44 5
The function I used:
public function store($homes, $member_id) {
foreach( $homes as $home ) {
$data[] = [ 'member_id' => $member_id, 'home_name' => $home ];
}
Home::insert( $data );
}
which works fine while inserting. However, I need to update all records for a given $member_id if the member_id already exists.
For example, if the $member_id is 5 and $homes is now array( 'home54' ), all other home_name that are previously stored for the $member_id 5 should be deleted. so that the following would only remain.
id home_name member_id
1 home54 5
You can use Laravel's upsert() method
Example:
Home::upsert([
['home_name' => 'home54', 'member_id' => 5, 'id' => 1],
['home_name' => 'home13', 'member_id' => 5, 'id' => 2],
['home_name' => 'home21', 'member_id' => 5, 'id' => 3],
], ['member_id', 'id'], ['home_name']);
This method consists of three arguments.
Values to insert/update
Columns that uniquely identify the values
The values that need to be updated
Please note that you need to use a unique composite key to use upsert() method.
Example from Seeder class:
$table->unique(['member_id','id']);
Reference from Laravel docs: https://laravel.com/docs/9.x/eloquent#upserts
You can use updateOrCreate method to achieve this
public function store($homes, $member_id) {
foreach( $homes as $home ) {
Home::updateOrCreate( 'member_id' => $member_id, 'home_name' => $home );
}
}

How to update all records in a table with Eloquent?

Solution
foreach($request->all() as $record){
EventViews::query()->updateOrCreate(['id'=>$record['id']], $record);
}
Question
How do I update a whole table by passing a request array? It should update existing rows and create new ones if id doesn't exist. If possible without having to loop over the whole table.
Attempts that don't work:
EventViews::query()->updateOrCreate($request->all());
.
DB::transaction(function ($request) {
foreach ($request->all() as $record) {
EventViews::updateOrCreate($record);
}
});
.
$model = new EventViews($request->all());
$model->fill($request->all())->save();
assuming your request payload looks something like
records[]=[id=1,name=foo,description=foo,c=1]&
records[]=[id=2,name=bar,description=bar,c=1]&
...
you could loop over it like:
$input = $request->input('records');
foreach($input as $record){
EventViews::query()->updateOrCreate(['id'=>$record['id']],$record);
}
if your request looks like:
1=[name=foo,description=foo,c=1]&
2=[name=bar,description=bar,c=1]&
...
where the parameter name is the id, then you could use:
$input = $request->input();
foreach($input as $key => $record){
EventViews::query()->updateOrCreate(['id'=>$key],$record);
}
updateOrCreate receives 2 parameters, the first is the constrains and the second is the data.
I don't know your request structure, but it's good practice verify it before throwing it into your database.
Example:
Model::query()->updateOrCreate(
['my_column' => $request->input('my_column')],
[*array of column/values of what should be updated*]
)]
If exists a Model with given my_column value, it will update it's value with the associative array passed on the second argument, otherwise it will create a new entry.
you can use this method :
$flight = Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99, 'discounted' => 1]
);
or
Flight::upsert([
['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
], ['departure', 'destination'], ['price']);
for get more information see this link:
https://laravel.com/docs/9.x/eloquent#upserts

Select multiple random column values from a two-dimensional array

I want to select 5 random ID's from my array of rows. Here is my array $test:
$test = [
['id' => 13, 'pets' => 8],
['id' => 15, 'pets' => 8],
['id' => 16, 'pets' => 10],
['id' => 17, 'pets' => 9],
['id' => 18, 'pets' => 10],
['id' => 19, 'pets' => 10],
['id' => 20, 'pets' => 0],
['id' => 21, 'pets' => 8],
['id' => 22, 'pets' => 9],
['id' => 23, 'pets' => 4],
['id' => 24, 'pets' => 0],
['id' => 40, 'pets' => 8],
['id' => 43, 'pets' => 2],
];
How can I select 5 random ID's from the array and put them into a string like this:
$ids = '13,17,18,21,43';
I've tried to use array_rand(), but it does not seem to work for my type of array. I'm not sure if there are any other built in PHP functions that can do this type of job or if I have to create my own function. It would be nice to have my own function like this to plug in the number of required values.
You can use array_column to only get the ID's and shuffle them.
Then use array_slice to get five items and implode.
$id = array_column($arr, "id");
Shuffle($id);
Echo implode(",", array_slice($id, 0, 5));
First extract the id column indexing also by the id, then pick 5 random ones, and finally implode into a comma separated list. Since keys must be unique, this has the added benefit of not returning duplicate ids if there happen to be duplicates in the array:
$ids = implode(',', array_rand(array_column($test, 'id', 'id'), 5));
For a function:
function array_rand_multi($array, $key, $num) {
return implode(',', array_rand(array_column($array, $key, $key), $num));
}
If you want random, unique ids in a random order, I recommend shuffling the array, then isolating upto 5 subarrays, then extracting the id values, then joining with commas. This way array_column() doesn't need to iterate the full array.
Code: (Demo)
shuffle($test);
echo implode(
',',
array_column(
array_slice($test, -5),
'id'
)
);
If you want random, unique ids and don't mind that they will be in the same order as your input rows, then array_rand() can be used.
#AbraCadaver's approach works by applying temporary keys to the input array, picking five random keys, then joining with commas. Because the values inside the rows are never used, null can also be used as array_column()'s second parameter. These approaches should not be used if duplicate ids need to be honored. In other words, because id values are being applied to the first level keys, php will automatically destroy any rows with duplicated ids -- because a single level of an array cannot contain duplicate keys.
One way to avoid potentially destroying data is to call array_rand() on the original indexes of the input array, then filter those unique indexes by 5 randomly selected indexes. (Demo)
echo implode(
',',
array_column(
array_intersect_key(
$test,
array_flip(array_rand($test, 5))
),
'id'
)
);
Finally, if you want 5 randomly selected, randomly ordered ids which may be selected more than once, then just make 5 iterated calls of array_rand(). (Demo)
for ($x = 0, $delim = ''; $x < 5; ++$x, $delim = ',') {
echo $delim . $test[array_rand($test)]['id'];
}
Or (Demo)
echo implode(
',',
array_map(
fn() => $test[array_rand($test)]['id'],
range(1, 5)
)
);
You can proceed like this (short example) :
<?php
$items = array(
array("id" => 43, "pets" =>2),
array("id" => 40, "pets" =>8),
array("id" => 24, "pets" =>0),
array("id" => 23, "pets" =>4),
);
$ids = $items[array_rand($items)]["id"].",".$items[array_rand($items)]["id"].",".$items[array_rand($items)]["id"];
echo $ids;
// Output Example : 24, 40, 23
?>
It will choose a random key from the main array ($items), example : 3, and output the "id" :
$items[3]["id"]
for this example.
Here is a demo : http://sandbox.onlinephpfunctions.com/code/32787091e341cdf8e172d96b065b14b3ca834846

Laravel database insert query

I'm trying to do simple insertion in database and im getting the following error
call_user_func_array() expects parameter 1 to be a valid callback, no
array or string given
The insertion code look like this
DB::insert('insert into users (id, name) values (?, ?)', array(1, 'Dayle'));
It's a basic query for laravel, but it won't work why?
DB::table('users')->insert(
array(
'id' => '1',
'name' => 'Dayle'
)
);
or
$values = array('id' => 1,'name' => 'Dayle');
DB::table('users')->insert($values);
But why are you inserting an ID? Should this not be an auto incremented value?
$user['id'] = 1;
$user['name'] = 'dale';
DB::table('users')->insert($user);
You can make simple like this
$val={
'id_user' => '< ID_USER >',
'title' => '< TITLE >',
'body' => '< BODY >',
}
Forum::create($val);
And its work

SQL Results as PHP Array

I am trying to solve this. Maybe this is absolutly incorrect, I need some help.
I have a table like this:
INSERT INTO `municipios` (`id`, `provincia`, `municipio`) VALUES (1, 1, 'Alegría-Dulantzi'), (2, 1, 'Amurrio'), (3, 1, 'Añana'), (4, 1, 'Aramaio'), (5, 1, 'Armiñón'),
And this is my handler:
$query = "SELECT * FROM municipios WHERE provincia='1'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$groups = array(
$row{'id'} => array(
'name' => $row{'municipio'},
'description' => 'Agrupación electoral de ' . $row{'municipio'},
'status' => 'public',
'enable_forum' => 1,
),
);
}
With this I got just the last result. I have tried another options, but doesn´t work.
Something like this should solve your issue:
$groups[] = array(
$row['id'] => array(
'name' => $row['municipio'],
'description' => 'Agrupación electoral de ' . $row['municipio'],
'status' => 'public',
'enable_forum' => 1,
),
);
However, may i suggest your use PDO. There is a pretty good article http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/ that should get you going in the right direction.
Is this an issue with the way you're appending the groups array? I think your overwriting the array every time u set a value. Try using array_push() to append to groups.
Let us know of that helps!
array_push()
http://php.net/manual/en/function.array-push.php

Categories