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.
Related
i have created student and subject models and their CRUD
how do i register a collection of subject_id for a student
i have created a new model 'Registration' with subject_id and student_id but i don't how to add a collection of subject_id's to students
This is my student model
class Student extends Model
{
protected $table = 'students';
protected $fillable = [
'firstname','middlename','lastname','index_no','parent_id',
'regular_or_weekend',
'course_id',
'nationality',
'image'
]
public function subjects()
{
return $this->hasMany(Subject::class);
}
}
this is my subject class
class Subject extends Model
{
protected $table = 'subjects';
protected $fillable = ['subject_code','subject_name','credit_hours'];
protected $cast =[
'credit_hours' => 'Integer',
];
public function student()
{
return $this->belongsTo(Student::class);
}
}
In has many relationships you should do something like this:
$student = Student::find(1);
$student->subjects()->createMany([
[
'subject_code' => 'code',
'subject_name' => 'name',
'credit_hours' => 'hours'
],
[
'subject_code' => 'code',
'subject_name' => 'name',
'credit_hours' => 'hours'
],
]);
Below is a piece of code from my Register Controller. As you can see, every field has a value, but its not inserting into database. I have configured default values to these fields in database, if values are not present. It gives row don't have default value. I am unable to figure out the problem. I also have all fields fillable in Models.
protected function create(array $data)
{
$user = Account::create([
'wallet' => $data['wallet'],
'email' => $data['email'],
'balance' => 0,
'uqid' => rand(10000000,99999999) ,
'ref' => 0,
]);
$gnl = General::first();
$track = Track::create([
'account_id' => $user->id,
'speed' => $gnl->dhs_free,
'balance' => 0,
'uqid' => rand(10000000,99999999) ,
'ref' => 0,
]);
Account Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Account extends Model
{
protected $fillable = ['wallet','uqid','ref','bstatus','refcom','email','verified'];
public function deposit()
{
return $this->hasMany('App\Deposit','id','account_id');
}
public function withdraw()
{
return $this->hasMany('App\Withdraw','id','account_id');
}
public function track()
{
return $this->hasMany('App\Track','id','account_id');
}
Track Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Track extends Model
{
protected $fillable = array( 'account_id','speed','withdraw','status');
public function account()
{
return $this->belongsTo('App\Account');
}
}
When using the create function, it seems you are not filling all the fields in the table.
Either, ensure you're assigning values to all fields in the create() function, or ensure there are default values in the database. In the builder, use ->default(0) or something.
There are few things which can be identified in your code :
Firstly the number and name of the columns in the Model and create method are different :
Account Model contains :
protected $fillable = ['wallet','uqid','ref','bstatus','refcom','email','verified'];
But your create contains :
'wallet' => $data['wallet'],
'email' => $data['email'],
'balance' => 0,
'uqid' => rand(10000000,99999999) ,
'ref' => 0,
Create does not contain bstatus, refcom and so on... columns but those are present in your Model and in the database table.
Similarly, Track Model contains :
protected $fillable = ['account_id','speed','withdraw','status'];
But its create contains :
'account_id' => $user->id,
'speed' => $gnl->dhs_free,
'balance' => 0,
'uqid' => rand(10000000,99999999) ,
'ref' => 0,
Now, if your non-specified columns in create() function do not have any default value specified in database, you will get :
Error : row don't have default value
Solution either add values to those columns in create() or mark those columns are nullable using a migration.
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;
});
I have a form that allows an authenticated user create a new conference.
This form will request the user information and some of this information introduced by the user should be stored in the Conference table, some in the "Conference_Category" table and some in the "RegistrationType" table.
So when the user submit the form "dd($request->all());" shows:
array:20 [▼
"_token" => "DbDKu3ryk4NdxKLr3aO132iHrE0O5b0XqfENk1"
"conference_name" => "Conference Name"
"conference_categories" => "1"
"conference_description" => "description"
"conference_creator_name" => "John"
"conference_creator_email" => "email#testemail.email"
"conference_creator_description" => "description"
"registration_type_name" => "registration type name"
"registration_type_description" => "registration type desc"
"registration_type_capacity" => "100"
]
DOUBT
My doubt is how to properly store this request information. Because its necessary to store the request data into 3 different tables to create a new conference:
In the "Conference" table is necessary to store: the conference_name, conference_description, conference_creator_id, conference_creator_name,conference_creator_email, conference_creator_description
In the "conference_category" table is necessary to store: the conference categories id's and the conference id
In the "RegistrationType" table is necessary to store:registration_type_name, registration_type_description and registration_type_capacity
I have a ConferenceController and I have the logic to create a new conference in the store() method of the ConferenceController. But for now I just have the part to store the request information on the Conference table.
Do you know how to also store the categories introduced by the user and the registration type in the respective tables (conference_category and RegistrationType)?
ConferenceController create method:
<?php
namespace App\Http\Controllers;
use App\Category;
use App\Conference;
use Illuminate\Http\Request;
class ConferenceController extends Controller
{
public function store(Request $request)
{
dd($request->all());
$this->validate($request, [
'conference_name' => 'required|max:255',
'conference_categories' => 'required|array|between:1,3',
'conference_startDate' => 'required',
'conference_creator_name' => 'required',
'conference_creator_email' => 'required|email|unique:users',
'conference_creator_description' => '',
'conference_registration_type_name' => 'required',
'confenrece_registration_type_description' => '',
'conference_registration_type_capacity' => 'required',
]);
$conference = Conference::create([
'name' => $request->conference_name,
'description' => $request->conference_description,
'startDate' => $request->conference_startDate,
'conference_creator_id' => Auth::user()->id,
'conference_creator_name' => $request->conference_creator_name,
'conference_creator_email' => $request->conference_creator_email,
'conference_creator_description' => $request->conference_creator_description
]);
}
}
The relationships relevants for this questions are:
Many to many between Conference and Categories (A conference can have many categories, so there is a third table conference_category)
one to many between User and Conference (A user can create many conferences)
one to many between Conference and RegistrationType (A conference can have many registration types)
Conference Model
class Conference extends Model
{
protected $fillable = [
'name', 'description', 'startDate', '...'
];
public function categories(){
return $this->belongsToMany('App\Category');
}
public function conference_creator(){
return $this->belongsTo('App\User', 'conference_creator_id');
}
public function registrationTypes(){
return $this->hasMany('App\RegistrationType', 'conference_id');
}
}
Category Model:
class Category extends Model
{
public function conferences(){
return $this->belongsToMany('App\Conference');
}
}
RegistrationType Model:
class RegistrationType extends Model
{
public function conference(){
return $this->belongsTo('App\Conference');
}
}
User Model:
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password'
];
protected $hidden = [
'password', 'remember_token',
];
public function conferences(){
return $this->hasMany('App\Conference');
}
}
For the Category you want a Many-to-Many relation. Because a Conference can have many Categories and a Category can have many Conferences. You have already set this up correctly in your Models.
After you have created your Conference you can add the categories to the Conference, this can be done using the Attach method(Assuming that the given ids do exist, if not you'll have to check that first):
$conference->categories()->attach($request->conference_categories);
For more information about Attach: Laravel Eloquent
For the RegistrationType, I assume from your Models that a Conference can have multiple RegistrationTypes and a RegistrationType can only have 1 Conference.
You will have to add the following $fillables to your RegistrationType Model:
protected $fillable = ['name', 'description', 'capacity', 'conference_id'];
After you have created your Conference you can create the RegistrationType:
RegistrationType::create([
'conference_id' => $conference->id,
'name' => $request->conference_registration_type_name,
'description' => $request->confenrece_registration_type_description,
'capacity' => $request->conference_registration_type_capacity
]);
End result:
$conference = Conference::create([
'name' => $request->conference_name,
'description' => $request->conference_description,
'startDate' => $request->conference_startDate,
'conference_creator_id' => Auth::user()->id,
'conference_creator_name' => $request->conference_creator_name,
'conference_creator_email' => $request->conference_creator_email,
'conference_creator_description' => $request->conference_creator_description
]);
$conference->categories()->attach($request->conference_categories);
RegistrationType::create([
'conference_id' => $conference->id,
'name' => $request->conference_registration_type_name,
'description' => $request->confenrece_registration_type_description,
'capacity' => $request->conference_registration_type_capacity
]);
Table 1(users):
id username password role created_at updated_at
1 jhon yz 1 sometime sometime
Table 2(role):
id role created_at updated_at
1 employee sometime sometime
what I want
id username password role created_at updated_at
1 jhon yz employee sometime sometime
Users Model:
class User extends Eloquent implements UserInterface, RemindableInterface {
public function role()
{
return $this->hasOne('role', 'id', 'role');
}
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
}
Roles Model:
class Role extends Eloquent {
protected $table = 'roles';
}
how do i get the role name in the view ? Is my relationship right
one role can be used by many users, like:
user1 can be admin
user2 can be admin too
user3 is a manager
user4 is a manager too
if thats the case then,..
Users Model:
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
public function role()
{
return $this->belongsTo('Role');
}
}
Roles Model:
class Role extends Eloquent {
protected $table = 'roles';
public function users()
{
return $this->hasMany('User');
}
}
then use:
User::with('role')->whereRole(1)->get(); // assuming that 1 = employee; this is eager loading
this will yield something like:
[
new User([
'id' => 1,
'username' => 'blahblah',
'password' => 'pass',
'role' => 1,
'created_at' => '0000-00-00',
'updated_at' => '0000-00-00',
'role' => new Role([
'id' => 1,
'role' => 'employee',
'created_at' => '0000-00-00',
'updated_at' => '0000-00-00'
])
])
]