I have default User model:
class User extends Authenticatable implements HasRoleContract
{
use Notifiable, HasRole;
}
With one relationship inside:
public function distributor() {
return $this->hasOne('App\DistributorContacts', 'distributor_id', 'id');
}
So, when user passed authorization I can not see this relation in object:
{{dd(Auth::user())}}
you may use ->with('distributor') on your user Object to get relationships loaded.
e.g.
$user = new User()->with('distributor');
dd($user->distributor);
or
Auth::user()->with('distributor');
Related
I want a relationship where two unrelated models are linked together with a linker model.
My tables are like:
card table
id(pk)
name
User table
id(pk)
username
password
card_id(fk)
Feature table
id(pk)
name
card_id(fk)
How can i define an eloquent relationship to access all the features of user's card from user model like this:
class User extends Model
{
use HasFactory;
public function features(){
return $this->relatonship_statement;
}
}
and when I tried in Card Model:
class Card extends Model
{
use HasFactory;
public function features(){
return $this->hasMany(Feature::class);
}
}
and in User model:
class User extends Model
{
use HasFactory;
public function card(){
return $this->belongsTo(User::class);
}
public function features(){
return $this->card->features;
}
}
I get error:
App\Models\User::features must return a relationship instance.
What you really want is an accessor function, not a relationship. This is how you would do to achieve what you want.
class User extends Model
{
use HasFactory;
protected $appends = ['features']; //to append features in the response json
public function card(){
return $this->belongsTo(Card::class); //editted User to Card
}
public function getFeatures(){ //accessor method
return $this->card->features()->get();
}
}
sample result after returning user in a controller function
return User::query()->with('card')->first();
However, the right way is to access the features through the Card Relationship because these two models have a direct relationship.
I am on a project with Laravel.
I have two database tables that are in a One-To-Many relationship with each other. They are joined by three conditions. How do I model this relationship in Eloquent?
I am not supposed to modify the database schema, since it has to remain backward compatible with other things.
I have tried the following, but it doesn't work.
The owning side:
use Illuminate\Database\Eloquent\Model;
class Route extends Model
{
public function trips()
{
return $this->hasMany('Trip', 'route_name,source_file', 'route_name,source_file')
}
}
The inverse side:
use Illuminate\Database\Eloquent\Model;
class Trip extends Model
{
public function routes()
{
return $this->belongsTo('Route', 'route_name,source_file', 'route_name,source_file');
}
}
I don't want to use "use Awobaz\Compoships\Compoships;"
You need to give hasMany() and belongsTo method the namespace of your models.
Something like 'App\Models\Trip' or Trip::class
class Route extends Model
{
public function trips()
{
return $this->hasMany('App\Models\Trip', 'route_name,source_file', 'route_name,source_file')
}
}
class Trip extends Model
{
public function routes()
{
return $this->belongsTo('App\Models\Route', 'route_name,source_file', 'route_name,source_file');
}
}
I have a User Model and a Role Model which are in many-to-many relation.
I have two roles: admin and manager.
I also have an Order Model. Managers need to have many orders. Where do I state such relations? Do I have to state it in the User Class?
Do I need to create separate models for Admins and Managers?
Managers & admins are a subset of your users, defined by their roles.
Therefore, we'll use scope to filter users who are managers by their roles.
App\Scopes\ManagerUserScope.php
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class ManagerUserScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* #param \Illuminate\Database\Eloquent\Builder $builder
* #param \Illuminate\Database\Eloquent\Model $model
* #return void
*/
public function apply(Builder $builder, Model $model)
{
//Assuming Your user has a relationship (has many) role
$builder->whereHas('role', function($roleQuery) {
//Assuming that in the role table, the manager role entry has ID 1
$roleQuery->where('id','=',1);
});
}
}
Then, we extend the User model to create a manager model which has the above scope automatically applied.
App\Models\Manager.php
namespace App\Models;
use App\Scopes\ManagerUserScope;
class Manager extends User {
/**
* The "booting" method of the model.
*
* #return void
*/
protected static function boot()
{
parent::boot();
static::addGlobalScope(new ManagerUserScope);
}
/**
* Relationship: Orders (Has many)
*/
public function orders()
{
return $this->hasMany('orders');
}
}
Your many-to-many relationship between User and Role can be perfectly described with belongsToMany Eloquent relation methods both ways. Also since each Order must have responsible manager for it we also have one-to-many relation between Manager and Order which will be described with hasMany/belongsTo methods.
So, your User model will have:
public function roles()
{
return $this->belongsToMany('App\Role');
}
public function orders()
{
return $this->hasMany('App\Order');
}
For your Role model:
public function users()
{
return $this->belongsToMany('App\User');
}
And lastly your Order model:
public function manager()
{
return $this->belongsTo('App\User');
}
There is no need to create a certain limitations (like "only users with role manager can have orders") on DB schema level, it's easier to implement in the code. So, for example, you might want to implement a method that will assign order to user and check his roles first.
I have the following SQL tables for example:
guards
guard_id guard_name guard_type
roles
role_id role_name security_priviledge
guard_roles
gr_id guard_id role_id
How would I define this relationship in Laravel?
You have to define two Models, App/Guard.php and App/Role.php and define their Many to Many relationship. For example:
On App/Guard.php:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Guard extends Model
{
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
On App/Role.php:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function guard()
{
return $this->belongsToMany('App\Guard');
}
}
Please consider this method of in the User model:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
use Cartalyst\Sentry\Users\Eloquent\User as SentryUserModel;
class User extends SentryUserModel implements UserInterface, RemindableInterface {
//[...]
public function company()
{
Log::info("SPOOFED", array($this->getSpoofedCompanyId()));
// == 1
if($this->getSpoofedCompanyId() > 0) {
return Company::find($this->getSpoofedCompanyId());
}
else {
return $this->belongsTo('Company');
}
}
This produces the following error:
LogicException
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
I guess I'm not allowed to return an object which has no relation? Is there any way to bypass this?
The reason is that I'm letting a superuser impersonate another user.