Problems with seeds in Laravel - php

My problem is the next one:
I have already done some seeds, and im trying to get the primary key to the another table/seed.
Here is the code i have problems:
$factory->define(App\Movimento::class,function(Faker\Generator $faker){
$Transportador=App\Transportador::pluck('TransportadorId');
$array =[
'MovimentoId' => $faker->randomNumber,
'Data' => $faker->date,
'Destino' => $faker->word,
'EMExp' => $faker->word,
'Transp' => $faker->randomNumber($Transportador)
];
return $array;
});
So the "Transp" is a Foreign Key and i want the same key has the "TransportadorId" from the other seed.
Here is the code how is clear from errors:
$factory->define(App\Transportador::class,function(Faker\Generator $faker){
$nbDigits='3';
$redDigits='9';
$array =[
'TransportadorId' => $faker->randomNumber($nbDigits),
'Nome' => $faker->text,
'Contribuinte' => $faker->randomNumber($redDigits)
];
return $array;
});
P.S-> I'm sorry for my bad English.

You can probably do:
$factory->define(App\Movimento::class,function(Faker\Generator $faker){
$Transportadores = App\Transportador::all();
$array =[
'MovimentoId' => $faker->randomNumber,
'Data' => $faker->date,
'Destino' => $faker->word,
'EMExp' => $faker->word,
'Transp' => $Transportadores->random()->TransportadorId
];
return $array;
});

Related

Returning empty object in Laravel resource instead of null

I do have a resource (DeviceResource) in my Laravel API which contains another resource (SimcardResource). There is a OnetoOne relationship between those resources but sometimes a device has no associated simcard.
If this is the case my DeviceResource returns for the simcard null instead of an empty json object.
I do need an empty json object because I present information called from my API in my Vue frontend by accessing an object e.g. like device.simcard.phone_number
My DeviceResource class looks like this:
public function toArray($request)
{
return [
'id' => $this->resource->id,
'model' => $this->resource->model,
'device_name' => $this->resource->device_name,
'operating_system' => $this->resource->operating_system,
'os_version' => $this->resource->os_version,
'emei' => $this->resource->emei,
'device_password' => $this->resource->device_password,
'purchase_date' => $this->resource->purchase_date,
'associated_worker' => $this->resource->associated_worker,
'remarks' => $this->resource->remarks,
'device_status_id' => $this->resource->device_status_id,
// 'simcard' => $this->resource->simcard ?: (object)[],
'simcard' => SimcardResource::make($this->whenLoaded('simcard')) ?: (object)[],
];
}
The commented section:
'simcard' => $this->resource->simcard ?: (object)[]
Works perfectly but returns all fields from my simcard table but I only need fields defined in my SimcardResource class so I tried the following:
'simcard' => SimcardResource::make($this->whenLoaded('simcard')) ?: (object)[]
But it still returns null instead of an empty json object.
Okay maybe its not the best solution but my DeviceResource class now looks like this:
public function toArray($request)
{
if (is_null($this->resource->simcard)) {
return [
'id' => $this->resource->id,
'model' => $this->resource->model,
'device_name' => $this->resource->device_name,
'operating_system' => $this->resource->operating_system,
'os_version' => $this->resource->os_version,
'emei' => $this->resource->emei,
'device_password' => $this->resource->device_password,
'purchase_date' => $this->resource->purchase_date,
'associated_worker' => $this->resource->associated_worker,
'remarks' => $this->resource->remarks,
'device_status_id' => $this->resource->device_status_id,
'simcard' => (object) [],
];
} else {
return [
'id' => $this->resource->id,
'model' => $this->resource->model,
'device_name' => $this->resource->device_name,
'operating_system' => $this->resource->operating_system,
'os_version' => $this->resource->os_version,
'emei' => $this->resource->emei,
'device_password' => $this->resource->device_password,
'purchase_date' => $this->resource->purchase_date,
'associated_worker' => $this->resource->associated_worker,
'remarks' => $this->resource->remarks,
'device_status_id' => $this->resource->device_status_id,
// 'simcard' => $this->resource->simcard ?: (object)[],
'simcard' => SimcardResource::make($this->whenLoaded('simcard')),
];
}
}
It is Laravel resource default behaviour that if you do not have any data than resource will also return you the null resource object. You have to manage it yourself in other way like by defining each parameter has null value that's it.
Laravel introduce best ways,for example whenLoaded,but try this
... ?? json_encode(new stdClass)

Retrive Bulk Inserted ids after insert() function in Laravel 6+

I Research a lot but Could not find any solution. So i am posting it Here
My problem is After Inserting bulk rows i want to get all the inserted ids to save the ids to another Pivot table.. Here is my code
$create_market = [];
$create_market_possibility = [];
foreach ($request->type0 as $key => $value) {
array_push($create_market, [
'market_id' => $value['market_id'],
'event_id' => $value['event_id'],
'name' => $value['name'],
'bet_min' => $value['min_bet'],
'bet_max' => $value['max_bet'],
'commission' => $value['commission'],
'type' => 0,
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now()
]);
}
foreach ($request->type1 as $key => $value1) {
array_push($create_market, [
'market_id' => $value1['market_id'],
'event_id' => $value1['event_id'],
'name' => $value1['name'],
'bet_min' => $value1['min_bet'],
'bet_max' => $value1['max_bet'],
'commission' => $value1['commission'],
'type' => 1,
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now()
]);
foreach ($value1['possibility'] as $key => $value2) {
array_push($create_market_possibility, [
// because i am not getting the inserted ids here i cant push it here
// that is the problem i am facing
'market_id' => $value1['market_id'],
'event_id' => $value1['event_id'],
'possibility' => $value2['possibility'],
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now()
]);
}
}
Market::insert($create_market);
// Here i want to retrive the last inserted all ids and put then in the obj of
[$create_market_possibility] array ...
if(count($create_market_possibility) > 0) {
MarketPossibility::insert($create_market_possibility);
}
$response = [
'status' => true,
'message' => 'Market Successfully Created'
];
return response()->json($response); //# sending response
i did this thing wher i was using create() for single insert
$id = Market::create($array)
It was returning me the object.. But in this case i have to insert multiple rows..
If there any other way to do it please let me know , Thank You!
1. For type0
You can run Market::insert($array) for type0 since there is no associated MarketPossibility
2. For type1,
You will have to create each Market one by one then associate it - you can use saveMany() to make it cleaner a faster:
$market = Market::create([...])
$new_market_possibility = [];
foreach ($value1['possibility'] as $key => $value2) {
$new_market_possibility[] = new App\MarketPossibility([...]);
}
$market->marketPossibilities()->saveMany($new_market_possibilities);
All that assuming that you have standard relations in place between Market and MarketPossibility

CodeIgniter-Access from model to controller

I have the following code in Model:
<?php
class Route_Model extends CI_Model
{
function __construct()
{
parent::__construct();
}
public function getRoute($date = array())
{
try {
$data = array(
'route' => array(
'id' => 1,
'name' => 'budapest-athens',
'price' => 150,
'id' => 2,
'name' => 'rome-madrid',
'pret' => 250,
'id' => 3,
'name' => 'belgrade-bucharest',
'price' => 180,
'id' => 4
)
);
return $data;
} catch (Exception $e) {
return $e->getMessage();
}
}
}?>
And I want to access array elements in my controller.
How can I access each field separately?
Something like $price = $this->data['price']?
Thank you!
You are returning an array with two levels, if you want to get the price from the array $data, simply do this in your controller:
$data = $this->route_model->getRoute($date);
$price = $data['route']['price'];
Please, note that your array is not well formed because you have repeated keys and this may cause problems
This array will never work since you're overwriting keys, I think you would want the following array:
$data = [
'route' => [
[
'id' => 1,
'name' => 'budapest-athens',
'price' => 150
], [
'id' => 2,
'name' => 'rome-madrid',
'price' => 250
], [
'id' => 3,
'name' => 'belgrade-bucharest',
'price' => 180
]
]
];
Next to that, your try / catch seems unnecessary here, there is no real try. It's a hard-coded array, so unless this will actually do some interactions there is no need for the try / catch.
Anyway, to receive this data in your controller you should do:
$this->load->model('Route_model');
$route = $this->Route_model->getRoute();
var_dump($route);
exit;
Now you will have this array. Another wonder, are you actually trying to grab all the routes in this array, or is there something you want to do with the $date parameter? Since right now it doesn't looks like it's used unless you stripped some code away.

Merge the inner array to the parent array using hash of cakephp

I have the following array
$array['projects'] = [
'name1' => [
'task' => [
'tags' => ['value1', 'value2'],
'email' => 'email2',
'description' => 'mpla'
],
'email' => 'email1',
'tags' => ['value1', 'value3'],
'title' => 'mpla'
]
];
Is there anyway I could use the Hash class of CakePHP 3 or maybe another class of CakePHP framework to achieve the following result:
$array['projects'] = [
'name1' => [
'email' => 'email2',
'tags' => ['value1', 'value2'],
'title' => 'mpla'
'desciption' => 'mpla'
]
];
If you also know anyother package that it can handle arrays and get my job done it will do.
Not sure that this can be easily achieved using Cake's Hash utility. You can easily extract the array items indexed by task using combine(), but not sure how you would then go about extracting the title values and combining those with the other array elements using Hash:-
Hash::combine($array, 'projects.{s}', 'projects.{s}.task');
Perhaps the simplest solution is to use a foreach loop like this:-
$data = [];
foreach ($array['projects'] as $value) {
$data['projects'] = $value['task'] + ['title' => $value['title']];
}

Converting undefined indexes to null in PHP

I'm not sure if the title of this question is necessarily the accurate description of what I need to do, but I'll go ahead and ask my question and see what everyone thinks...
Basically, I am receiving data from a source that I have no control over, and I need to transpose it into a suitable format for inserting into my database using CakePHP. So, here's how I'm doing it:
public function submitApp($data) {
$array = array(
'Student' => array(
'name' => $data['name'],
'email' => $data['email'],
'phone' => $data['phone'],
'address' => $data['address'],
'dob' => $data['dob'],
'gender' => $data['gender']
),
'Application' => array(
'course_id' => $data['course_id'],
'question1' => $data['question1'],
'question2' => $data['question2'],
'question3' => $data['question3'],
'question4' => $data['question4'],
),
'ApplicationQualification' => $data['Qualifications']
);
// Logic to save $array goes here
}
The problem is that sometimes not all of the keys in $data will be submitted to my app but I still want my app to work with what it gets.
I know that I can wrap each key in a conditional like this:
if (!isset($data['name'])) { $data['name'] = null; }
...and then building the array, but this seems like a pretty clumsy way of doing it. Is there a more efficient way to do this?
You could use a simple ternary statement
'name' => array_key_exists('name', $data) ? $data['name'] : null
Alternatively, you can set up a default array and then merge the given values in
$defaults = [
'name' => null,
'email' => null,
// etc
];
$data = array_merge($defaults, $data);

Categories