i have a relationship that i try to insert with the relationship into the model every thing is fine when i just add phone numbers but when i add the secound field which is type_id i cant handle it because it wont insert the secound field into table here is how i do it in my controller store i want my user to be able to send unlimited phone numbers and each of them have a type_id how can i achive that
:
public function store(StoreHome $request)
{
$validated = $request->all();
if (!$validated) {
return $this->sendError('Validation Error.', $validated->errors());
}
$home = Home::create($validated);
$phones = [];
$type_id = [];
$numbers = $request->input('phones');
$type_id = $request->input('type_id');
foreach($numbers as $number => $item){
$phones[] = [
'phone' => $number
];
$types[] = [
$type_id[] = [
'type_id' => $type_id[$item]
]
];
}
$home->phones()->createMany($phones);
return new HomeResource($home);
You pass $phones to createMany, this variable does not contain any type_id because you put them into $types variable which, moreover is not declared (I suppose you mispelled $type_id = []; instead of $types = [];
Example solution;
$datas = [];
foreach($numbers as $number => $item){
array_push($datas, [$number => $type_id[$item]]);
}
foreach ($datas as $key => $value) {
Home::create([
'phone' => $key,
'type_id' => $value
]);
}
Related
I have the code if there is the same name in 2nd foreach, then the same name is not displayed, but I don't know how to keep the same name not displayed?.
$arr = [];
foreach ($respon_tel['item'] as $item) {
$proyek = [
'nama_proyek' => $item['judul_kontrak'],
'from' => 'Another API'
];
foreach($model as $m){
if(trim(strtolower($item['judul_kontrak'])) == trim(strtolower($m['nama_proyek']))){
// ????
}
}
$arr[] = $proyek;
}
return $arr;
You can get all the nama_proyek's from the $model then you can check if the current $item's judul_kontrak is in that set:
$models = collect($model)
->map(fn ($i) => trim(strtolower($i['nama_proyek'])));
foreach ($respon_tel['item'] as $item) {
if (! $models->contains(trim(strtolower($item['judul_kontrak'])))) {
$arr[] = [
'nama_proyek' => $item['judul_kontrak'],
'from' => 'Another API'
];
}
}
Or you could get creative with the Collection methods:
collect($respon_tel['item'])
->pluck('judul_kontrak', 'judul_kontrak')
->map($f = fn ($item) => trim(strtolower($item)))
->diff(
collect($model)->pluck('nama_proyek')->map($f)
)->map(function ($item, $key) {
return [
'nama_proyek' => $key,
'from' => 'Another API',
];
})->values();
hi im using this php code
$data = new $models([
'number' => $row[0],
'name' => $row[1],
]);
like this its working fine but what i want is that i dont know the keys 'number' and 'name' what if i want them come from array like this ..
$array = ['name','number','anything'];
$data = new $models([
foreach($array as $key => $arr)
{
$arr => $row[$key];
}
]);
how can i do something like this ..
calling foreach inside creating new class ..
thanks ..
<?php
class Foo{}
$className='Foo';
$array = ['name','number','anything'];
$row = ['name_v', 'number_v', 'anything_v'];
$foo = new $className();
foreach(array_combine($array, $row) as $k => $v){
$foo->$k = $v;
}
print(json_encode($foo));
So long as they have the same number of elements in the order that you want, just combine them:
$array = ['name', 'number', 'anything'];
$data = new $models(array_combine($array, $row));
You can do it in one line:
$data = new $models(array_combine(['name', 'number', 'anything'], $row));
I have an array
$array = [
0=>1
1=>Jon
2=>jon#email.com
3=>2
4=>Doe
5=>doe#email.com
6=>3
7=>Foo
8=>foo#email.com
]
What I`d like to do is to add and extra value to each value.
Something like this so I can access it when looping through the array
$array=[
0=>1[id]
1=>Jon[name]
2=>jon#email.com[email]
3=>2[id]
4=>Doe[name]
5=>doe#email.com[email]
6=>3[id]
7=>Foo[name]
8=>foo#email.com[email]
]
I guess it would be a multidimensional array?
What would be the proper way of doing it?
Loop through array and check key of items and based of it create new array and insert values in it.
$newArr = [];
foreach($array as $key=>$value){
if ($key % 3 == 0)
$newArr[] = ["id" => $value];
if ($key % 3 == 1)
$newArr[sizeof($newArr)-1]["name"] = $value;
if ($key % 3 == 2)
$newArr[sizeof($newArr)-1]["email"] = $value;
}
Check result in demo
yes just use 2 dimension array
$arr = array();
$arr[0][0] = "1"
$arr[0][1] = "Jon"
$arr[0][2] = "jon#email.com"
$arr[1][0] = "2"
$arr[1][1] = "Doe"
$arr[1][2] = "doe#email.com"
Since an array is a map in PHP, I'd recommend to use it like a map or to create a class holding the data.
$arr = array();
$arr[0]['ID'] = 1;
$arr[0]['name'] = "John";
$arr[0]['mail'] = "john#email.com;
Example for one class:
<?PHP
class User
{
public $id;
public $name;
public $mail;
function __construct($ID,$name,$mail)
{
$this->id = $ID;
$this->name = $name;
$this->mail = $mail;
}
}
?>
and then you can simply use it like that:
<?PHP
require_once("User.php");
$user = new User(1,"Mario","maio290#foo.bar");
echo $user->name;
?>
A simple, yet often-used solution is to use multidimensional array with string keys for better readability:
$array = [
0 => [
'id' => 1,
'name' => 'Jon',
'email' => 'jon#email.com',
],
1 => [
'id' => 2,
'name' => 'Doe',
'email' => 'doe#email.com',
],
2 => [
'id' => 3,
'name' => 'Foo',
'email' => 'foo#email.com',
],
];
You can loop through this like so:
for ($array as $item) {
// $item['id']
// $item['name']
// $item['email']
}
But since PHP is an object-oriented language, I'd suggest creating a class for the data-structure. This is even easier to read and you can very easily add functionality related to the entity etc.
class Person {
public $id;
public $name;
public $email;
function __construct($id, $name, $email) {
$this->id = $id;
$this->name = $name;
$this->email = $email;
}
}
$array = [
0 => new Person(1, 'Jon', 'jon#email.com'),
1 => new Person(2, 'Doe', 'doe#email.com'),
2 => new Person(3, 'Foo', 'foo#email.com'),
];
You can loop through this like so:
for ($array as $person) {
// $person->id
// $person->name
// $person->email
}
Use array_map on the result of array_chunck this way:
$array=array_map(function($val){ return array_combine(['id','name','email'],$val);}, array_chunk($array,3));
note that the second parameter of array_chunk depend of the number of columns and the first array used in array_combine too
see the working code here
You can also do like this:
$array1 = ["name"=>"alaex","class"=>4];
$array2 = ["name"=>"aley","class"=>10];
$array3 = ["student"=>$array1,"student2"=>$array2];
print_r($array3);
How to return all array values inside foreach loop. Return is working fine and no error but is only one record. If i have 10 records in database, It supposed to be all records. What did i missed this code? thanks for your help.
PHP
function myfunction(){
$query ="SELECT * from tbl_data";
$stmt = $this->getConnection()->prepare($query);
$stmt->execute();
foreach ($stmt->fetchAll() as $value) {
//custom value
$customval = 1;
$array = array([
"ID" => $value['ID'],
"name" => $value['name'],
"staus" => $value['status'],
"customval" => $customval,
]);
}
return $array;
}
You are currently actually just overwriting $array, you need to push the new data to it instead.
$array = array();
foreach ($stmt->fetchAll() as $value) {
//custom value
$customval = 1;
$array[] = [
"ID" => $value['ID'],
"name" => $value['name'],
"staus" => $value['status'],
"customval" => $customval,
];
}
return $myArray;
You are assigning $array on every iteration, overwriting the previous value.
Maybe you want to create an array of arrays:
$array = array();
foreach ($stmt->fetchAll() as $value) {
//custom value
$customval = 1;
array_push($array, array([
"ID" => $value['ID'],
"name" => $value['name'],
"staus" => $value['status'],
"customval" => $customval,
]));
}
return $array;
You are only getting one value returned because you are overwriting the value of the array each time.
You need to push the new values each loop iteration.
$myArray = array();
foreach ($stmt->fetchAll() as $value) {
//custom value
$customval = 1;
array_push($myArray, array([
"ID" => $value['ID'],
"name" => $value['name'],
"staus" => $value['status'],
"customval" => $customval,
]));
}
return $myArray;
This will return an array of arrays.
I'm trying something really simple and yet doesn't work. I have one controller where selecting from one database to show some info for user. Now I'm trying in this same controller to select from second table to show some other info but I get Undefined variable...
This is the part of controller which is problematic
public function orderView( $orderId, $userId ) {
$order = self::$user->orders()->where('order_id', $orderId)->first();
$keys = Keys::all();
if (!$order) {
App::abort(404);
}
$userID = $order['user_id'];
$orderID = $order['order_id'];
$public_key = $keys['public_key'];
$private_key = $keys['private_key'];
$options = array(
"public_key" => $public_key,
"private_key" => $private_key,
"orderID" => $orderID,
"userID" => $userID
);
What I have added here is
$keys = Keys::all();
$public_key = $keys['public_key'];
$private_key = $keys['private_key'];
....
"public_key" => $public_key,
"private_key" => $private_key,
The error is Undefined index: public_key
Keys::all() returns an Illuminate\Database\Eloquent\Collection.
In order to access a single item of the Collection, you either must iterate the collection and access them singularly, or take one item specifically with Collection's functions, such as first().
For example:
public function orderView($orderId, $userId)
{
$order = self::$user->orders()->where('order_id', $orderId)->first();
$keys = Keys::all();
if (! $order) {
App::abort(404);
}
$options = [];
foreach ($keys as $key)
{
$options[] = [
'public_key' => $key->public_key,
'private_key' => $key->private_key,
'userID' => $order->user_id,
'orderID' => $order->order_id
];
}
return $options;
}
You can find more information about Illuminate Collection methods here.