Seed data with relationship in Laravel - php

I'm trying to seed my Laravel 5.6 application through faker factory, I went through the link and little bit confused, As I have some basic static data, like for example I've a company model:
class Company extends Model {
use SoftDeletes, HasDataSearchTable, HasSlug;
protected $fillable = [
'name', 'code_link', 'slug', 'establishment', 'parent_id', 'website', 'updates', 'user_id', 'tracked', 'verified', 'active', 'premium', 'status'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'created_at','updated_at','deleted_at'
];
public function roles()
{
return $this->belongsToMany('Noetic\Plugins\Conxn\Models\Variables\Company\Role', 'company_role_relation', 'company_id', 'role_id')->withTimestamps();
}
}
And a relational role model:
class Role extends Model
{
use SoftDeletes , HasDataSearchTable;
protected $table='company_role';
protected $fillable = [
'name', 'parent_id'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'created_at','updated_at','deleted_at'
];
}
and respective database, I'm following the laravel convention, Now I want to seed the data:
I've particular set of roles which I'm seed in manually,
class CompanyRoleSeed extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('company_role')->insert([
['name' => 'Contractor', 'parent_id' => null],
['name' => 'Consultant', 'parent_id' => null],
['name' => 'Manufacturer', 'parent_id' => null],
['name' => 'Miscellaneous', 'parent_id' => null],
['name' => 'Owner', 'parent_id' => null],
['name' => 'Supplier', 'parent_id' => null],
]);
}
}
For company I want to create factory so I did:
$factory->define(Company::class, function (Faker $faker) {
return [
'name' => $faker->company,
'code_link' => rand(5, 10),
'slug' => str_slug($faker->company),
'about' => $faker->paragraphs(),
'establishment' => $faker->randomElement('2015', '2016', '2017', '2018'),
'parent_id' => $faker->randomElement(null, '1', '2', '3'),
'website' => $faker->url,
'user_id' => $faker->randomElement('1', '2', '3', '4', '5'),
'updates' => $faker->paragraphs(),
'tracked' => $faker->boolean,
'verified' => $faker->boolean,
'active' => $faker->boolean,
'premium' => $faker->boolean,
'status' => $faker->randomElement('saved', 'draft')
];
});
And in company seed I'm having:
class CompanySeed extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory(Company::class, 10)->create()->each(function ($company) {
$company->roles()->save(); // Don't now how to execute here
});
}
}
Help me at place $company->roles()->save(); What should I do over here.
Any guidance or improvisation welcome.

You can query which roles you want to assign to the companies and related them to the created records like this:
class CompanySeed extends Seeder
{
public function run()
{
$contractorRole = Role::whereName('Contractor')->firstOrFail();
$ownerRole = Role::whereName('Owner')->firstOrFail();
factory(Company::class, 10)->create()->each(function ($company) use ($contractorRole, $ownerRole) {
$company->roles()->attach([
$contractorRole->id,
$ownerRole->id
]);
});
}
}
You can check the doc for relating records https://laravel.com/docs/5.6/eloquent-relationships#inserting-and-updating-related-models

before answering your question you should know that Laravel's documentation explains how to do this.
But in order to save a related Model you first need to create a fake one, or in your case relate a role you have already created. In order to do this you could first create a Role factory using something like this:
$factory->define(App\Role::class, function (Faker $faker) {
$randomRoleAlreadyCreated = \App\Role::all()->random();
return [
'name' => $randomRoleAlreadyCreated->name,
'parent_id' => $randomRoleAlreadyCreated->parent_id
];
});
As you can see on Role factory I created I pull a random Role since you stated that you already created them manually, so if you choose one randomly then your companys will be related to one of your roles randomly!
Once you have: Roles created in DB, factory of roles, you could relate random roles to a company using the factory to save a random instance.
factory(Company::class, 10)->create()->each(function ($company) {
$company->roles()->save(factory(App\Role::class)->make()); // Don't now how to do here
});
Update
If you want to save multiple roles for each company you could do this:
factory(Company::class, 10)->create()->each(function ($company) {
// Instead of 4 you could also create a random number
// using $numberOfRolesToAttach = rand($min,$max)
for($i = 1; $i <= 4; $i++) :
$company->roles()->save(factory(App\Role::class)->make());
endfor;
});

Related

What causes the 'Unknown format "factory"' error in this Laravel 8 app?

I am working on a Laravel 8 app with users and posts.
The objective is to create a bunch of posts (I already have users).
namespace Database\Factories;
// import Post model
use App\Models\Post;
// import User model
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
class PostFactory extends Factory {
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = Post::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition() {
return [
'title' => $this->faker->sentence(3),
'description' => $this->faker->text,
'content' => $this->faker->paragraph,
'user_id' => $this->faker->factory(App\Models\User::class),
];
}
}
The problem
I run php artisan tinker then Post::factory()->count(100)->create() in the terminal and I get:
InvalidArgumentException with message 'Unknown format "factory"'
UPDATE
I replace my return statement with:
return [
'title' => $this->faker->sentence(3),
'description' => $this->faker->text,
'content' => $this->faker->paragraph,
'user_id' => User::factory(),
];
I get this in the terminal:
Class 'Database\Factories\UserFactory' not found
Questions:
Where is my mistake?
Does the fact that I get the error Class 'Database\Factories\UserFactory' not found mean that I need to
create a UserFactory factory? Because there isn't one. (I wanted
to create posts, not users).
I don't suppose there is $this->faker->factory(..).
You can do
'user_id' => App\Models\User::factory()->create()->id,
EDIT:
'user_id' => App\Models\User::factory(),
Creating a UserFactory factory and using the below return statement did the trick:
return [
'title' => $this->faker->sentence(3),
'description' => $this->faker->text,
'content' => $this->faker->paragraph,
'user_id' => User::factory(),
];
So, the PostFactory class looks like this:
class PostFactory extends Factory {
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = Post::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition() {
return [
'title' => $this->faker->sentence(3),
'description' => $this->faker->text,
'content' => $this->faker->paragraph,
'user_id' => User::factory(),
];
}
}

Laravel not working method updateOrCreate

The user has a profile setting. I want if the user changes some fields to be updated. But I have a new column created and should be updated. Maybe someone is not doing it right. Help please. Thank you very much.
Controller
public function profile_settings_post(Request $request){
// Auth Specialist
$user = Auth::user();
// Data Specialist Validate
$data = $request->validate([
'first_name' => 'nullable|string',
'last_name' => 'nullable|string',
'phone_number' => 'nullable|integer',
'gender' => 'nullable',
'date_of_birth' => 'nullable',
'about_me' => 'nullable',
'address' => 'nullable',
'city' => 'nullable|string',
'country' => 'nullable|string',
'postal_code' => 'nullable|integer',
]);
$profile = $user->profile_settings()->updateOrCreate($data);
$profile->save();
// RETURN REDIRECT PROFILE SETTINGS INDEX
return redirect()->route('frontend.specialist.profile.settings');
}
User Model
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public static function countPercent($count, $maxCount){
//one percent
$one_percent = $maxCount / 100;
// $count how much is percent
$percent = $count / $one_percent;
return $percent;
}
// 1 User have 1 profile settings (ONE TO ONE)
public function profile_settings(){
return $this->hasOne(Profile_Settings::class);
}
}
Profile_Settings Model:
class Profile_Settings extends Model
{
// Fill in db
protected $fillable = [
'first_name', 'last_name', 'phone_number',
'gender', 'date_of_birth', 'about_me',
'address', 'city', 'country', 'postal_code',
];
// Profile settigns model belongs to User
public function user(){
return $this->belongsTo(User::class);
}
}
When I edit some kind of field. A new field is created in the database
profile settings database not working update create new columns
You probably didn't read carefully how works updateOrCreate
It performs update based on the condition that you're passing in and updates the fields, that you want, so you will have to pass 2 arrays.
Example from Laravel's webitse
// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99, 'discounted' => 1]
);
So this means we are updating all rows, where 'departure' = 'Oakland', 'destination' = 'San Diego' and setting price to 99$.
I your case you should decide the condition, when you should perform update query, it will be 1st array, and also decide which fields should be updated, put it in 2nd array.

Return many object in my json response using resource

I'm kinda new to Laravel and I hope someone we'll be able to give me some help.
I apologize for my english
So I'm trying to develop an application with some friends to manage our food by sending alert when the peremption date is near.
I'm developing the API, the actual structure is this way:
A user,
A product,
A basket containing the user_id, the product_id and of course the peremption date.
So now when I make a call to get the User 'stock' on my API I wish I could get something like this:
{
'id' : 1,
'peremption_date': XX-XX-XX,
'product' : {
'id' : 3,
'name': bblablabala,
'brand' : blablabala
},
'id' : 2,
'peremption_date': XX-XX-XX,
'product' : {
'id' : 4,
'name': bblablabala,
'brand' : blablabala
},
}
So I took a look on resources and saw that if I define the right relations, this could do the stuff for my output.
I'll link you my actual class declarations and their resources:
User:
//user.php
class User extends Authenticatable
{
use Notifiable, HasApiTokens;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function baskets()
{
return $this->hasMany(Basket::class);
}
}
Product:
//Product.php
class Product extends Model
{
protected $table = 'products';
protected $fillable = ['code_barre', 'product_name', 'generic_name', 'brand', 'quantity'];
public function basket()
{
return $this->belongsToMany(Basket::class);
}
}
//productResource.php
class ProductResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'code_barre' => $this->code_barre,
'product_name' => $this->product_name,
'generic_name' => $this->generic_name,
'brand' => $this->brand,
'quantity' => $this->quantity,
'created_at' => (string) $this->created_at,
'updated_at' => (string) $this->updated_at,
];
}
}
Basket:
//Basket.php
class Basket extends Model
{
protected $table = 'baskets';
protected $fillable = ['user_id', 'product_id', 'dlc_date'];
public function user()
{
return $this->belongsTo(User::class);
}
public function product()
{
return $this->hasOne(Product::class);
}
}
//BasketResource.php
class BasketResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'dlc_date' => (string) $this->dlc_date,
'created_at' => (string) $this->created_at,
'updated_at' => (string) $this->updated_at,
'product' => $this->product
];
}
}
So when I try to store a new basket in my store method:
//BasketController.php
public function store(Request $request)
{
$this->product->storeProduct($request->input('code_barre'));
$att = DB::table('products')
->where('code_barre', '=', $request->input('code_barre'))
->first();
$basket = Basket::create([
'user_id' => $request->user()->id,
'product_id' => $att->id,
'dlc_date' => $request->input('dlc_date')
]);
return new BasketResource($basket);
}
I get the following error (this one)
saying than products.id_basket does not exist and its right, it's not supposed to exist. This is Basket who have a product_id. so I know this is coming from the relationship I declared but I can't figure how to do it right.
Can someone come and save me ???
Thanks a lot, I hope you understood me !
Wish you a good day
As I look at your Basket model, it seems you have to change your:
public function product()
{
return $this->hasOne(Product::class);
}
to:
public function product()
{
return $this->belongsTo(Product::class);
}
Because you have product_id in your baskets table. To use hasOne() relation, you will need to remove product_id from baskets table and add basket_id to products table, because hasOne() relation is something like hasMany(), only calling ->first() instead of ->get()

Laravel updateOrCreate on OneToOne relationShip

in my web application i have this models:
InstagramAccount.php
UserPageFeed.php
each InstagramAccount has one record into UserPageFeed and each UserPageFeed belongs to one record into InstagramAccount, then that's one to one relationship,
PROBLEM:
my below code couldn't update existing row on table and create again
$userSelectedPage = InstagramAccount::whereUsername('my_page')->first();
$userPageFeeds = new UserPageFeed();
$userSelectedPage->account()->updateOrCreate([
'instagram_account_id' => $userPageFeeds->id, //exsiting row
'page_name' => 'test',
'feeds' => 'test',
'cache_time' => Carbon::now()->addHour(6),
]);
or this code:
$userSelectedPage = InstagramAccount::whereUsername('content.world')->first();
$salam = $userSelectedPage->account()->updateOrCreate([
'instagram_account_id' => $userSelectedPage->id,
'page_name' => 'aaaaaaa',
'feeds' => 'ddd',
'cache_time' => Carbon::now()->addHour(6),
]);
user_page_feeds table structure:
id ->Primary
instagram_account_id ->Index
feeds
page_name
cache_time
created_at
updated_at
with this index:
"Keyname":user_page_feeds_instagram_account_id_foreign "Column":instagram_account_id
instagram_accounts table structure:
id ->Primary
user_id ->Index
uid
fid
proxy
avatar
username
password
checkpoint
account_data
people_data
status
created_at
updated_at
InstagramAccount model:
class InstagramAccount extends Model
{
protected $guarded = ['id'];
protected $casts = [
'account_data' => 'array',
'people_data' => 'array'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function account()
{
return $this->hasOne(UserPageFeed::class);
}
}
UserPageFeed model:
class UserPageFeed extends Model
{
public $incrementing = false;
protected $guarded = ['id'];
protected $casts = [
'feeds' => 'array'
];
public function account()
{
return $this->belongsTo(InstagramAccount::class,'instagram_account_id');
}
}
You have to use updateOrCreate() with two separate parameters:
$userSelectedPage->account()->updateOrCreate(
['instagram_account_id' => $userPageFeeds->id],
[
'page_name' => 'test',
'feeds' => 'test',
'cache_time' => Carbon::now()->addHour(6),
]
);
The first parameter contains the attributes that Laravel uses to find the existing
account.
The second parameter contains the attributes that Laravel uses to create or update the account.

Extends User plugin by adding a profile does not render tab either new added fields in OctoberCMS

I've follow all the steps on the Extending User plugin screencast but for some reason I can not see "Profile" tab and either new added fields. Since I used the second approach, the easy one, this is what I've done:
Create the plugin and models and so on under Alomicuba namespace
Create and make the needed changes to the files as explained in video:
Plugin.php
<?php namespace Alomicuba\Profile;
use System\Classes\PluginBase;
use RainLab\User\Models\User as UserModel;
use RainLab\User\Controllers\Users as UsersController;
/**
* Profile Plugin Information File
*/
class Plugin extends PluginBase
{
public $requires = ['RainLab.User'];
/**
* Returns information about this plugin.
*
* #return array
*/
public function pluginDetails()
{
return [
'name' => 'Profile',
'description' => 'Add extra functionalities for Alomicuba WS by extends RainLab User',
'author' => 'DTS',
'icon' => 'icon-users'
];
}
public function boot()
{
UserModel::extend(function($model){
$model->hasOne['profile'] = ['Alomicuba\Profile\Models\Profile'];
});
UsersController::extendFormFields(function ($form, $model, $context){
if ($model instanceof UserModel)
return;
$form->addTabFields([
'pinCode' => [
'label' => 'PIN',
'tab' => 'Profile'
],
'phone2' => [
'label' => 'Teléfono (2)',
'tab' => 'Profile'
],
'phone3' => [
'label' => 'Teléfono (3)',
'tab' => 'Profile'
],
'phone4' => [
'label' => 'Teléfono (4)',
'tab' => 'Profile'
]
]);
});
}
}
add_profiles_fields_to_user_table.php
<?php namespace Alomicuba\Profile\Updates;
use Schema;
use October\Rain\Database\Updates\Migration;
class AddProfilesFieldsToUserTable extends Migration
{
public function up()
{
Schema::table('users', function($table)
{
$table->integer('pinCode')->unsigned();
$table->dateTime('pinCodeDateTime');
$table->integer('phone2')->unsigned()->nullable();
$table->integer('phone3')->unsigned()->nullable();
$table->integer('phone4')->unsigned()->nullable();
});
}
public function down()
{
$table->dropDown([
'pinCode',
'pinCodeDateTime',
'phone2',
'phone3',
'phone4'
]);
}
}
version.yaml
1.0.1: First version of Profile
1.0.2:
- Created profiles table
- create_profiles_table.php
- add_profiles_fields_to_user_table.php
Profile.php (Model)
<?php namespace Alomicuba\Profile\Models;
use Model;
/**
* Profile Model
*/
class Profile extends Model
{
/**
* #var string The database table used by the model.
*/
public $table = 'alomicuba_profile_profiles';
/**
* #var array Relations
*/
public $belongsTo = [
'user' => ['RainLab\User\Models\User']
];
// This method is not need anymore since I'll use the second approach
public static function getFromUser($user)
{
if ($user->profile)
return $user->profile;
$profile = new static;
$profile->user = $user;
$profile->save();
$user->profile = $profile;
return $profile;
}
}
But when I edit a existent user I didn't see the 'Profile' tab and also didn't see any new added field. See image below:
Any advice around this? Did I miss something?
Also I have a few question around plugin extends:
How do I add a required field to the register form?
How do I display each new added field on the account form?
I haved tested your code on my machine you need to write
$require instead of $requires in plugin.php
please check documentation
http://octobercms.com/docs/plugin/registration#dependency-definitions
and when extendFormFields() method called for UserController you need to specify that you only want to extends fields for UserModel not for other
if (!$model instanceof UserModel)
return;
so plugin.php code look like this
<?php namespace Alomicuba\Profile;
use System\Classes\PluginBase;
use RainLab\User\Models\User as UserModel;
use RainLab\User\Controllers\Users as UsersController;
/**
* Profile Plugin Information File
*/
class Plugin extends PluginBase
{
public $require = ['RainLab.User'];
/**
* Returns information about this plugin.
*
* #return array
*/
public function pluginDetails()
{
return [
'name' => 'Profile',
'description' => 'Add extra functionalities for Alomicuba WS by extends RainLab User',
'author' => 'DTS',
'icon' => 'icon-users'
];
}
public function boot()
{
UserModel::extend(function($model){
$model->hasOne['profile'] = ['Alomicuba\Profile\Models\Profile'];
});
UsersController::extendFormFields(function ($form, $model, $context){
if (!$model instanceof UserModel)
return;
$form->addTabFields([
'pinCode' => [
'label' => 'PIN',
'tab' => 'Profile'
],
'phone2' => [
'label' => 'Teléfono (2)',
'tab' => 'Profile'
],
'phone3' => [
'label' => 'Teléfono (3)',
'tab' => 'Profile'
],
'phone4' => [
'label' => 'Teléfono (4)',
'tab' => 'Profile'
]
]);
});
}
}
and in add_profiles_fields_to_user_table.php
for dropping column write following code
Schema::table('users', function($table)
{
$table->dropDown([
'pinCode',
'pinCodeDateTime',
'phone2',
'phone3',
'phone4'
]);
}

Categories