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'
])
])
]
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'
],
]);
I am now coding a simple pizza ordering app with laravel.
Here are my current coding:
class Order extends Model {
protected $table = 'orders';
protected $primaryKey = 'id';
public $timestamps = false;
protected $fillable = ['pizzaid', 'date'];
}
class Order extends JsonResource {
public function toArray($request) {
return [
'id' => $this->id,
'pizzaid' => $this->pizzaid,
'date' => $this->date,
'pizzadata' => PizzaResource::collection(Pizza::where('id', $this->pizzaid)->get()),
];
}
}
class Pizza extends Model {
protected $table = 'pizzas';
protected $primaryKey = 'id';
public $timestamps = false;
protected $fillable = ['name', 'price', 'detail'];
}
class Pizza extends JsonResource {
public function toArray($request) {
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
'picture' => $this->picture,
'detail' => $this->detail,
];
}
}
As you can see here, every order resource must show pizza resource referenced by pizzaid. But for every order resource, my code executes 2 sqls of order and pizza. I want to executed only 1 sql. How can I fix my code?DB Table 'orders' has already foreign key with 'pizzas'.
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.
Basically I have a groups table with id and name,
I have another table with users_groups with id, group_id and user_id
I'm try to save when a user is created to the users_groups table, but when I use this code it saves what it can in the groups table. Is there something I'm doing wrong?
Account controller (saving user to db and set group to id 1)
$user = User::create(array(
'firstName' => $firstName,
'lastName' => $lastName,
'dateOfBirth' => $dateOfBirth,
'gender' => $gender,
'email' => $email,
'username' => $username,
'password' => Hash::make($password),
'code' => $code,
'active' => 0
));
Group::create([
'user_id' => $user->id,
'group_id' => '1' //1 is not assigned
]);
Group Model
class Group extends Eloquent
{
protected $fillable = array('name');
// DEFINE RELATIONSHIPS --------------------------------------------------
// define a many to many relationship
// also call the linking table
public function users() {
return $this->belongsToMany('User', 'users_groups', 'group_id', 'user_id');
}
}
User Model
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $fillable =array('email', 'username', 'password', 'password_temp', 'code', 'active', 'firstName','lastName','gender','dateOfBirth');
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
// Each User BELONGS to many Groups
// Define our pivot table also
public function groups() {
return $this->belongsToMany('Group', 'users_groups', 'user_id', 'group_id');
}
}
All information about saving relations can be found here
You need attach()
$user = User::create(array(
'firstName' => $firstName,
// ...
));
$user->groups()->attach(1); // 1 being the group_id
I tried with the default user table for Laravel Auth purpose,
Now i am changing it to the admin Table
So i refereed here
Accordingly i tried to change the Table name as admin in the auth.php
'model' => 'User',
'table' => 'users',
to
'model' => 'AdminModel',
'table' => 'admin',
And in the AdminModel i have protected $table = 'admin';
And i got the error
Class AdminModel contains 6 abstract methods and must therefore be declared abstract or implement the remaining methods (Illuminate\Auth\UserInterface::getAuthIdentifier, Illuminate\Auth\UserInterface::getAuthPassword, Illuminate\Auth\UserInterface::getRememberToken, ...)
Is there anything is should change rather than here ?
Here is my AdminModel :
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class AdminModel extends Eloquent implements UserInterface, RemindableInterface
{
protected $table = 'admin';
protected $fillable = array('UserName', 'Password');
public $timestamps = true;
public static $rules = array();
}
Update :
I replaced with appropriate changes
i.e.,
use UserTrait, RemindableTrait;
Solved,
It didn't ended in success
I checked
if (Auth::attempt(array('UserName' => $UserName, 'password' => $password)))
{
return Redirect::intended('dashboard');
}
else
{
$queries = DB::getQueryLog();
print_r(end($queries));
}
And it is always printing the query like this
Array ( [query] => select * from `admin` where `UserName` = ? limit 1 [bindings] => Array ( [0] => a ) [time] => 1 )
What might be the issue ?