How to call scope in model? - laravel

I have the following method in model:
public function announcements()
{
return $this->categories()->with("announcements");
}
And in the same model:
public function scopeActive($query)
{
return $query->where('votes', '>', 100);
}
Hot to call this local scope in model for:
return $this->categories()->with("announcements")->active(); ?

I assume the categories is an relation on this model and the announcements is a relation on the categories model.
Then you can try:
return $this->active()->categories->with("announcements")
$this->active() will return the active records of this model.
->categories will get the related categories
->with("announcements") will eager load the announcements of all the categories.
This will return an eloquent query builder instance.

Related

How to write this same code and get same data in eloquent relationship ... laravel

How to write this same code and get same data in eloquent relationship
public function index(){
$data = DB::table('categories')
->join('subcategories', 'categories.id', 'subcategories.cat_id')
->select('categories.*', 'subcategories.*')->paginate(5);
return view ('admin.subcategory.index', compact('data'));
}
You need to create hasMany relationship between Category and Subcategory.
Category model
class Category extends Model
{
public function subcategories()
{
return $this->hasMany('App\Subcategory','cat_id','id');
}
}
Now you can call with('subcategories')
Category::with('subcategories')->paginate(5)

Laravel how to get only relation data

this is my User.php relation code
public function activities()
{
return $this->hasMany(Activities::class, 'builder');
}
and this is my query to get only relation data
return User::whereHas('activities', fn($query) => $query->where('user_id', 1))
->paginate();
but it returns only user data without appling any relation, and its pagination not get to use pluck
i have also tried this
User::where('username', request()->username)->has('activities')->paginate();
but i need only get relation data not user with relation, and i prefer do it with whereHas
You need to create reverse relation for Activities model:
class Activities extends Model
{
// ...
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id');
}
}
And get all the activities using Activities builder:
$paginated = Acitivities::query()
->whereHas('user', static function(Builder $userQuery) {
$userQuery->where('name', request()->username); // Think about security!
})
->paginate();
Note: All the models must be named in singular (e.g. Activity, User, Product and etc.).

Laravel 5.8 local query scope with pivot table, return the related models

I have Services that have a many-to-many relationship to People as contacts, connected by a services_contacts pivot table and I'm attempting to create a local scope query on the Service model to return the primaryContacts():
public function scopePrimaryContacts($query)
{
$pivot = $this->contacts()->getTable();
return $query->whereHas('contacts', function ($q) use ($pivot) {
return $q->where("{$pivot}.is_primary", true);
});
}
This returns the services, where I need it to return the people that are related as is_primary on the pivot table itself. I'd like to be able to call $this->primaryContacts on my Service model, like I can call $this->contacts to get any/all contacts. Any ideas where to go from here? Here are the relationships... contacts on the Service model:
public function contacts()
{
return $this->belongsToMany(Person::class, 'services_contacts', 'service_uuid', 'person_uuid')
->withPivot('is_primary', 'is_active', 'contact_type_uuid')
->withTimestamps();
}
And services on the Person model:
public function services()
{
return $this->belongsToMany(Service::class, 'services_contacts', 'person_uuid', 'service_uuid');
}
I wouldn't make this a scope, I'd make a second relationship function but with some additional params.
Service Model
public function primaryContact()
{
return $this->belongsToMany(Person::class, 'services_contacts', 'service_uuid', 'person_uuid')
->wherePivot('is_primary', true)
->wherePivot('is_active', true);
}

Select column from relations relation in laravel

I'm trying to do eager loading using with() method, I only want to get selected column from relations relation, how can I do that ? . I'm using polymorphic relation.
Draft::with(["user:id,username","article:id,locale","article.articleable:title"])->where([
["user_id",$user_id],
["is_suspended",1]
])->get();
Draft Model
public function article()
{
return $this->belongsTo("App\Models\Article");
}
Article Model
public function drafts()
{
return $this->hasMany("App\Models\Draft", "article_id", "id");
}
public function articleable()
{
return $this->morphTo();
}
other models which has polymorphic relation with Article model
public function articles()
{
return $this->morphMany("App\Models\Article", "articleable");
}
This has been fixed in Laravel 5.7.6: https://github.com/laravel/framework/pull/25662
In order for this to work, you also have to select the id column:
Draft::with('user:id,username', 'article:id,locale', 'article.articleable:id,title')
^^
->where([
['user_id', $user_id],
['is_suspended', 1]
])->get();

Laravel | Using Eloquent hasManyThrough

I have a table called invoiceDetails that has item_id as foreign key from another table called items which has category_id as foreign key from table called categories.
I want to do that following using eloquent:
$result = InvoiceDetail::groupBy('item_id')
->selectRaw('sum(qty) as qty, item_id')->with('item', 'category')->get();
but I am getting error:
Call to undefined relationship [category] on model [App\InvoiceDetail].
Here's my relation inside Category model:
public function invoiceDetail() {
return $this->hasManyThrough('App\InvoiceDetail', 'App\Item', 'category_id', 'item_id');
}
Any suggestions?
Not sure you would even need a hasManyThrough relation here, unless you want to fetch all InvoiceDatail objects belonging to all items which in turn belong to the Category. That part is not clear from your question.
But in your example you are fetching items with their category from distinct item_id.
The reason this is not working is because you are trying to fetch the category relation from the InvoiceDetail object, which does not exist.
->with('item', 'category')
You want to load the Category based on the item relation, not based on the InvoiceDetail, try the dot notation (given that you did define the other relations)
->with('item.category')
Relations should be like this:
class InvoiceDetail extends Model
{
public function item()
{
return $this->belongsTo(\App\Item::class);
}
}
class Item extends Model
{
public function invoiceDetails()
{
return $this->hasMany(\App\InvoiceDetail::class);
}
public function category()
{
return $this->belongsTo(\App\Category::class);
}
}
class Category extends Model
{
public function items()
{
return $this->hasMany(\App\Item::class);
}
public function invoiceDetails()
{
return $this->hasManyThrough(\App\InvoiceDetail::class, \App\Item::class, 'category_id', 'item_id');
}
}
You would want to use the hasManyThrough if, for example, you have a Category and you want to load all the InvoiceDetails directly.
dd($category->invoiceDetails);

Resources