nested relation with condition in laravel - laravel

I have 3 models
User - Role- Permission
User
class User extends Model
{
protected $fillable = [
'name', 'email', 'password',
];
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
Role
class Role extends Model
{
protected $fillable = ['name' , 'label'];
public function users()
{
return $this->belongsToMany(User::class);
}
public function permissions()
{
return $this->belongsToMany(Permission::class);
}
}
Permission
class Permission extends Model
{
protected $fillable = ['name' , 'label'];
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
I want get List of users whose permissions were updated on a specific date
I know I sould use something like below but I dont know exatly how to use Where
$users = User::with('roles.permissions')->orderBy('name', 'asc')->paginate(25);
thanks alot

Use whereHas():
$users = User::whereHas('roles.permissions', function($query) use($date) {
$query->whereDate('permission_role.updated_at', $date);
})->orderBy('name', 'asc')->paginate(25);

Related

Search in Laravel relation using json column

I have problem with search in json column.
I have 3 relations:
products
feature products
feature_values
My tables:
products: https://ibb.co/1dgjT6m
feature products: https://ibb.co/K9f74Wn
feature_values: https://ibb.co/rc3zG5W
My migrations:
Product:
class Product extends Model implements Presentable
{
....
public function featureProducts()
{
return $this->hasMany(FeatureProduct::class, 'product_id');
//return $this->belongsToMany(Feature::class, 'feature_product', 'id');
}
}
FeatureProduct
class FeatureProduct extends Model
{
protected $table = "feature_product";
protected $with = [
'values'
];
public function values()
{
return $this->belongsTo(FeatureValue::class, 'feature_values_ids', 'id');
}
}
FeatureValues:
class FeatureValue extends Model
{
use SoftDeletes,
Translatable;
protected $fillable = [
'feature_id',
'value'
];
protected $dates = [
'created_at',
'updated_at',
'deleted_at'
];
protected $translatable = [
'value'
];
public function feature(): BelongsTo
{
return $this->belongsTo(Feature::class);
}
public function getAdminUrlAttribute(): AbstractAdminUrlPresenter
{
return new FeatureValueUrlPresenter($this);
}
}
I need to show products with features and assigned features_values
I heve problem with search in json column: feature_product. feature_values_ids
When I have INT in this column, then this is working fine:
public function values()
{
return $this->belongsTo(FeatureValue::class, 'feature_values_ids', 'id');
}
When I have:
["1", "2","3"]
I haven't any results :(
Haw can I repair it?

Laravel eloquent multiple levels of relations

Alright so I am basically trying to retrieve all animal_registry codes based on a user ID.
Idea is that
1 user has many jobs.
Jobs are consisted of many "Jobs data".
Jobs data has many "Animal registry" entries.
These are my relations
Image relations link (click)
And these are my relations in Laravel
class User
{
public function jobs()
{
return $this->hasMany('App\Models\RegistryJobs', 'employee', 'id');
}
}
class RegistryJobs extends Model
{
protected $table = "registry_jobs";
protected function jobsData()
{
$this->hasManyThrough('App\Models\AnimalRegistry', 'App\Models\RegistryJobsData', 'id', 'animal_registry_id');
}
}
class RegistryJobsData extends Model
{
protected $table = "registry_jobs_data";
public function jobs()
{
$this->belongsTo('App\Models\RegistryJobs', 'id', 'registry_jobs_id');
}
public function animals()
{
$this->hasMany('App\AnimalRegistry', 'id', 'animal_registry_id');
}
}
class AnimalRegistry extends Model
{
protected $table = "animal_registry";
}
And now I am trying to query it from a controller in a way
$data = User::whereHas('jobs', function ($query) {
$query->where('id', 1);
})->get();
But I am unable to access the properties from the animal_registry.
Can you try like this :
public function animals(){
return $this->hasManyThrough('App\Registry_Jobs_data','App\Registry_Jobs', 'employee',
'registry_jobs_id', 'id' ,'id')->join('//Do the joining')->select();
}
Check the hasManyThrough i am not sure..

Cannot Extend Laravel Model

I have 2 models. The User model, and the relationship works correctly, I use tinker, and I can see the application that is associated with the user.
User::find(4)->application
However, the application will not return the user - in tinker I get null, whats worse, if I try to access rep in tinker, I get Bad Method Exception Call
Application::find(8)->user
is null
Note: I have an id column in users which I "find" users. and there is "ucid" column in users that I have defined as the primaryKey in Application.
Application Model:
class Application extends Model
{
protected $data = [
'data' => 'array'
];
protected $primaryKey = 'ucid';
protected $fillable = [
'ucid', 'data'
];
public function user()
{
return $this->belongsTo(User::class,'ucid');
}
public function rep()
{
return 'Test';
}
}
User Model
class User extends Authenticatable
{
public function application()
{
return $this->hasOne(Application::class,'ucid');
}
}
What am I missing?
Can you try this? Let me know if it works..
Application Model
class Application extends Model
{
protected $data = [
'data' => 'array'
];
protected $primaryKey = 'ucid';
protected $fillable = [
'ucid', 'data'
];
public function user()
{
return $this->hasOne(User::class, 'ucid');
}
public function rep()
{
return 'Test';
}
}
User Model
class User extends Authenticatable
{
public function application()
{
return $this->belongsTo(Application::class, 'ucid', 'ucid');
}
}
As you see I switched hasOne and belongsTo in your models.
Also.. third argument on hasOne of Application Model is not required since value from $primaryKey will be used since its defined, however you have to specify the third argument in belongsTo of User model

Laravel 5.5 Relationships

I'm trying to implement relationships between models and i recieve "Trying to get property 'products' of non-object" and i don't understand why, because i used this before in the same way and it's worked fine.
The logic of relationship is that 1 Merchant hasMany Products
this is the code that i'm using:
Merchant Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Merchant extends Model {
protected $table = "merchants";
protected $fillable = [
'merchant_id', 'merchant_name', 'secret_key', 'merchant_address', 'merchant_phone', 'merchant_admin',
'merchant_contact', 'merchant_mail', 'merchant_description', 'enable', 'created_at', 'updated_at'];
public function users() {
//many to many
return $this->belongsToMany('App\User');
}
public function branchOffices() {
return $this->hasMany('App\BranchOffice', 'merchant_id', 'merchant_id');
}
public function products() {
return $this->hasMany('App\Products', 'merchant_id', 'merchant_id');
}
public function transactions() {
return $this->hasMany('App\Transaction', 'merchant_id', 'merchant_id');
}
public function readers() {
return $this->hasMany('App\Reader', 'merchant_id', 'merchant_id');
}
}
Product Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
protected $table = "products";
protected $fillable = [
'id', 'barcode', 'description', 'price', 'currency_id', 'merchant_id', 'branch_id',
'enable', 'created_at', 'updated_at'];
public function merchants() {
return $this->belongsTo('App\Merchant', 'merchant_id', 'merchant_id');
}
public function currencies() {
return $this->belongsTo('App\Currency', 'iso_4712', 'currency_id');
}
public function branch_sectors() {
return $this->belongsToMany('App\BranchSector');
}
}
And this is the method in ProductController:
public function merchantProducts() {
$products = Merchant::find('merchant_id')->products;
return $products;
}
If someone can help me i'll be very thankfull.
Thanks in advance!!
Assume merchant is not guaranteed existing in database giving merchant id, it is better off to check if merchant exists, and retrieves its products if so.
$products = collect();
$merchant = Merchant::find($merchant_id);
if($merchant) {
$products = $merchant->products;
}
return $products;
all!!
Finally i solved this problem using resources in this way:
public function merchantProducts(Request $request) {
$merchant_id = $request->merchant_id;
$products = Product::where('merchant_id', $merchant_id)->paginate(15);
return ProductResource::collection($products);
}
Thanks to all!!

Eloquent Model has parent model

I have a Model called User with stuff like name, country and some relationships.
Now I want a Model, e.g. Vendor, having all the same functions and variables as a User including some More stuff
I thought I could to it this was:
class User extends Model implements AuthenticatableContract
{
use Authenticatable; SoftDeletes;
protected $dates = ['deleted_at', 'last_login'];
protected $fillable = [
'name',
'password',
'country',
];
protected $hidden = ['password'];
public function logs()
{
return $this->hasMany('App\Log');
}
}
And the Vendor Model:
class Vendor extends User
{
protected $fillable = [
'description'
];
public function user() {
return $this->belongsTo('App\User');
}
public function products()
{
return $this->hasMany('App\Product', 'vendor_id');
}
The Controller checks the role of the user and loads a user model or a vendor model:
if(Auth::user()->role > 1)
$user = Vendor::where('user_id', Auth::user()->id)->first();
else
$user = Auth::user();
return $user->load('logs');
But the load call fails for a vendor. I was able to join the fields of a user inside a vendor but I also need the functions of it.
The problem was that the logs function checks a field that doesn't exists.
Using this functions works:
public function logs()
{
return $this->hasMany('App\Log', 'user_id', get_called_class() !== get_class() ? 'user_id' : 'id');
}

Resources