Laravel: Factory Fake Car Data - php

I created a new factory in Laravel called "CarFactory.php" and I want to use https://github.com/pelmered/fake-car.
This is the fake data that I will insert into my database using Tinker:
return [
'name' => $this->faker->vehicleBrand(),
'founded' => $this->faker->biasedNumberBetween(1998,2017, 'sqrt'),
'description' => $this->faker->paragraph()
];
In the Laravel usage code, I'm not sure where to put this (e.g. Car Model, CarFactory):
$faker->addProvider(new \Faker\Provider\Fakecar($faker));
$v = $faker->vehicleArray();
return [
'vehicle_type' => 'car',
'vin' => $faker->vin,
'registration_no' => $faker->vehicleRegistration,
'type' => $faker->vehicleType,
'fuel' => $faker->vehicleFuelType,
'brand' => $v['brand'],
'model' => $v['model'],
'year' => $faker->biasedNumberBetween(1998,2017, 'sqrt'),
];
Help is needed to know how to set this up.

Related

How to create mongodb collection on runtime while executing Yii2 code?

I need to create mongodb collection while executing code, by checking whether the collection is exists or not.
I tried below things
Yii::$app->db->createCommand()-> createCollection("collection_name");
but collection not created.
Please help.
Issue resolved..
Yii::$app->db->createCommand()->createCollection("collection_name")->execute();
and index will added for collection as,
$collectionName = Yii::$app->db->getCollection("collection_name");
$collectionName->createIndexes([
'key' => ['id' => 'int'],
'name' => 'id_index'
],
[
'key' => ['id' => 'int', 'category' => 'text'],
'name' => 'id_category_index',
]);

Laravel: Edit value only if it appears in the request?

in my app the user can update the info of stripe connected account, however I ONLY want to actullay update the value of the fields that appear in the request payload, I could do this with a simple if check but the way I update the stripe array method makes this issue more complicated .
Is there any syntax sugar or trick to make this easier.
How my update method looks;
public function editConnectedAccount(Request $request)
{
$account = Account::retrieve($request->connectedAccountId);
Account::update(
$request->connectedAccountId,
[
'type' => 'custom',
'country' => 'ES',
'email' => $request->userEmail,
'business_type' => 'individual',
'tos_acceptance' => [ 'date' => Carbon::now()->timestamp, 'ip' => '83.46.154.71' ],
'individual' =>
[
'dob' => [ 'day' => $request->userDOBday, 'month' => $request->userDOBmonth, 'year' => $request->userDOByear ],
'first_name' => $request->userName,
'email' => $request->userEmail,
'phone' => $request->userPhone,
'last_name' => $request->userSurname,
//'ssn_last_4' => 7871,
'address' => [ 'city' => $request->userBusinessCity, 'line1' => $request->userBusinessAddress, 'postal_code' => $request->userBusinessZipCode, 'state' => $request->userBusinessCity ]
],
'business_profile' =>
[
'mcc' => 5812, //got it
'description' => '',
//'url' => 'https://www.youtube.com/?hl=es&gl=ES', //got it
],
'capabilities' => [
'card_payments' => ['requested' => true],
'transfers' => ['requested' => true],
],
]
);
return response()->json([
'account' => $account,
], 200);
Consider using a Form Request where you preform validation. This will neaten up your controller for a start and also make validation (never trust user input!) reusable.
Assuming validation is successful, calling $request->validated() from inside your controller method will return only the fields present and validated. You can then use either fill($request->validated()) or update($request->validated()).

Automated tests in jenkins object instantiation errors Using Laravel phpunit

I am running automated tests in jenkins on an aws linux server using nginx and php7.3. When the tests are run I am getting the following errors
1) Tests\Feature\admin\EventManagementTest::test_admin_can_edit_event_and_view_in_event_list
Error: Call to a member function path() on null
/var/lib/jenkins/workspace/answers-integration/tests/Feature/admin/EventManagementTest.php:134
2) Tests\Feature\admin\EventManagementTest::test_admin_can_soft_delete_event_and_does_not_appear_on_event_list
Error: Call to a member function path() on null
/var/lib/jenkins/workspace/answers-integration/tests/Feature/admin/EventManagementTest.php:190
Function path() is located in my Event model
On my local environment, everything works fine. Every test passes
Objects are not being instantiated and I have no ideas as to why
The following code is where it's failing to instantiate the object with an eloquent query
$event = Event::with('event_categories', 'event_topics')->find(1);
This happens to the majority of my tests. Below is the full test code
namespace Tests\Feature\admin;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
use \App\Event;
class EventManagementTest extends TestCase
{
use WithFaker, DatabaseMigrations;
public function setUp(): void
{
parent::setUp();
$this->seed();
}
public function test_admin_can_create_event_and_view_in_event_list()
{
//login as admin
$admin = $this->signInAsAdmin();
$attributes = [
'event_name' => $this->faker->name,
'event_description' => $this->faker->paragraph,
'event_start_date_time' => $this->faker->date('Y-m-d H:i:s'),
'event_end_date_time' => $this->faker->date('Y-m-d H:i:s'),
'organisation_name' => $this->faker->company,
'location' => $this->faker->address,
'contact_name' => $this->faker->name,
'contact_phone' => $this->faker->phoneNumber,
'contact_email' => $this->faker->email,
'contact_link' => $this->faker->url,
'venue' => $this->faker->address,
'event_categories' => [1,2],
'event_topics' => [2,3]
];
//create new event
$this->post('/admin/events', $attributes);
//retrieve event from database
$event = Event::with('event_categories', 'event_topics')->find(1);
//ensure the event data is in the database
$this->assertDatabaseHas('events', ['event_name' => $attributes['event_name'], 'event_description' => $attributes['event_description']]);
//ensure the data is in the pivot tables for categories
foreach ($event->event_categories AS $event_category){
$this->assertDatabaseHas('content_category_event', [
'event_id' => $event_category->pivot->event_id,
'content_category_id' => $event_category->pivot->content_category_id
]);
}
//ensure the data is in the pivot tables for tags
foreach ($event->event_topics AS $event_topics){
$this->assertDatabaseHas('content_tag_event', [
'event_id' => $event_topics->pivot->event_id,
'content_tag_id' => $event_topics->pivot->content_tag_id
]);
}
//make sure the title appears on the group list
$this->get('/admin/events')->assertSee($attributes['event_name']);
}
public function test_admin_can_edit_event_and_view_in_event_list()
{
//login as admin
$admin = $this->signInAsAdmin();
$attributes = [
'event_name' => $this->faker->name,
'event_description' => $this->faker->paragraph,
'event_start_date_time' => $this->faker->date('Y-m-d H:i:s'),
'event_end_date_time' => $this->faker->date('Y-m-d H:i:s'),
'organisation_name' => $this->faker->company,
'location' => $this->faker->address,
'contact_name' => $this->faker->name,
'contact_phone' => $this->faker->phoneNumber,
'contact_email' => $this->faker->email,
'contact_link' => $this->faker->url,
'venue' => $this->faker->address,
'event_categories' => [1,2],
'event_topics' => [2,3]
];
//create new event
$this->post('/admin/events', $attributes);
//retrieve event from database
$event = Event::with('event_categories', 'event_topics')->find(1);
$attributes_edit = [
'event_name' => $this->faker->name,
'event_description' => $this->faker->paragraph,
'event_start_date_time' => $this->faker->date('Y-m-d H:i:s'),
'event_end_date_time' => $this->faker->date('Y-m-d H:i:s'),
'organisation_name' => $this->faker->company,
'location' => $this->faker->address,
'contact_name' => $this->faker->name,
'contact_phone' => $this->faker->phoneNumber,
'contact_email' => $this->faker->email,
'contact_link' => $this->faker->url,
'venue' => $this->faker->address,
'event_categories' => [3,2],
'event_topics' => [2,1]
];
//update event
$this->put($event->path(), $attributes_edit);
//retrieve event from database
$event = Event::with('event_categories', 'event_topics')->find(1);
//ensure the event data is in the database
$this->assertDatabaseHas('events', [
'event_name' => $attributes_edit['event_name'],
'location' => $attributes_edit['location']
]);
//ensure the data is in the pivot tables for categories
foreach ($event->event_categories AS $event_category){
$this->assertDatabaseHas('content_category_event', [
'event_id' => $event_category->pivot->event_id,
'content_category_id' => $event_category->pivot->content_category_id
]);
}
//ensure the data is in the pivot tables for tags
foreach ($event->event_topics AS $event_topics){
$this->assertDatabaseHas('content_tag_event', [
'event_id' => $event_topics->pivot->event_id,
'content_tag_id' => $event_topics->pivot->content_tag_id
]);
}
//make sure the title appears on the group list
$this->get('/admin/events')->assertSee($attributes_edit['event_name']);
}
public function test_admin_can_soft_delete_event_and_does_not_appear_on_event_list()
{
//login as admin
$admin = $this->signInAsAdmin();
$attributes = [
'event_name' => $this->faker->name,
'event_description' => $this->faker->paragraph,
'event_start_date_time' => $this->faker->date('Y-m-d H:i:s'),
'event_end_date_time' => $this->faker->date('Y-m-d H:i:s'),
'organisation_name' => $this->faker->company,
'location' => $this->faker->address,
'contact_name' => $this->faker->name,
'contact_phone' => $this->faker->phoneNumber,
'contact_email' => $this->faker->email,
'contact_link' => $this->faker->url,
'venue' => $this->faker->address,
'event_categories' => [1,2],
'event_topics' => [2,3]
];
//create new event
$this->post('/admin/events', $attributes);
$event = Event::with('event_categories', 'event_topics')->find(1);
$this->delete($event->path());
//check the record has been soft deleted
$this->assertSoftDeleted('events', ['event_name' => $attributes['event_name']]);
//make sure the event name does not appear in event list
$this->get('/admin/users')->assertDontSee($attributes['event_name']);
}
}
EDIT
A further update doing a dd($this->post('/admin/events', $attributes)) I get the following error:
exception: Illuminate\Session\TokenMismatchException^ {#3806
#message: "CSRF token mismatch."
#code: 0
#file: "./vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php"
#line: 83
trace: {
How can a token be passed during a test?
Any help would be greatly appreciated
Regards
Danny
I found the solution to this problem from the following post
TokenMismatchException in Laravel's auth form

Create Associative Array with Foreach, Insert into existing Associative Array

Hello.
I currently have a problem with the AWS Route-53 API. To create a record you need to call a function, which itself needs an array of inputs.
I want to create a record set here and for that I have some POST values. One of them, $_POST['record_value'], is a textarea and has multiple lines. I loop through them. This is to enable multiple values for one record. The code is as follows when you hardcode it as one value in ResourceRecords;
$result = $this->route53->changeResourceRecordSets([
'ChangeBatch' => [
'Changes' => [
[
'Action' => 'CREATE',
'ResourceRecordSet' => [
'Name' => $recordName,
'ResourceRecords' => [
[
'Value' => $recordValue
],
],
'TTL' => $recordTtl,
'Type' => $recordType,
],
],
],
'Comment' => 'Routing Record Set',
],
'HostedZoneId' => $this->zone,
]);
Hower. I want to make ResourceRecords dynamically. For every line in the textarea I need a new set of the following part of the code;
[
'Value' => $recordValue
],
What I thought is the following;
$newData = [];
foreach(explode("\r\n", $recordValue) as $valLine) {
$newData[] = ["Value" => $valLine];
}
$result = $this->route53->changeResourceRecordSets([
'ChangeBatch' => [
'Changes' => [
[
'Action' => 'CREATE',
'ResourceRecordSet' => [
'Name' => $recordName,
'ResourceRecords' => [
$newData
],
'TTL' => $recordTtl,
'Type' => $recordType,
],
],
],
'Comment' => 'Routing Record Set',
],
'HostedZoneId' => $this->zone,
]);
However, this seems to return an exception: Found 1 error while validating the input provided for the ChangeResourceRecordSets operation:↵[ChangeBatch][Changes][0][ResourceRecordSet][ResourceRecords][0] must be an associative array. Found array(1).
Am I building the array wrong or am I doing this wrong alltogether?
$newData is already an array, you don't need to wrap it in another array.
'ResourceRecords' => $newData,

Cakephp3 able to save data but cannot save associations

Hi so I'm trying to save data through Cakephp3 framework. I have two tables Measures and MeasuresUsers. Measures has many MeasuresUsers
$data = [
'name' => $this->request->data['name'],
'description' => $this->request->data['description'],
'deleted' => $this->request->data['deleted'],
'chart_type' => $this->request->data['chart_type'],
'public' => $this->request->data['public'],
'user_id' => $this->request->data['user_id']
];
$measure = $this->Measures->newEntity($data,['associated' => ['MeasuresUsers']]);
$measure['measures_users'] = [
'user_id' => $user['id'],
'chart_type' => $this->request->data['chart_type'],
'deleted' => $this->request->data['deleted'],
'public' => $this->request->data['public']
];
$this->Measures->save($measure)
I'm able to save data into Measures table but not into the associative table (MeasuresUsers). I'm not sure what I'm missing here, any help or comments is appreciated!
#HarryM. is close, but you want to put your data into the $data array before creating the entity (the associated tag is kinda pointless if you're not providing that data!), and since it's a hasMany relation, I think you need to have the data in an array of arrays:
$data = [
'name' => $this->request->data['name'],
'description' => $this->request->data['description'],
'deleted' => $this->request->data['deleted'],
'chart_type' => $this->request->data['chart_type'],
'public' => $this->request->data['public'],
'user_id' => $this->request->data['user_id'],
'measures_users' => [
[
'user_id' => $user['id'], // Should this be $this->request->data['user_id'] instead?
'chart_type' => $this->request->data['chart_type'],
'deleted' => $this->request->data['deleted'],
'public' => $this->request->data['public'],
],
],
];
$measure = $this->Measures->newEntity($data, ['associated' => ['MeasuresUsers']]);
$this->Measures->save($measure);
Coming from CakePHP 2.x, I see your associate model is MeasuresUsers.
When you're setting the associated data in
$measure['measures_users'] = [
'user_id' => $user['id'],
'chart_type' => $this->request->data['chart_type'],
'deleted' => $this->request->data['deleted'],
'public' => $this->request->data['public']
];
Trying changing $measure['measures_users'] to $measure['MeasuresUsers']:
$measure['MeasuresUsers'] = [
'user_id' => $user['id'],
'chart_type' => $this->request->data['chart_type'],
'deleted' => $this->request->data['deleted'],
'public' => $this->request->data['public']
];
CakePHP's model conventions usually assume camel casing of what you have in the database e.g. DB Table it movie_tickets and Cake would expect is as MovieTicket unless otherwise declared in the Model itself.

Categories