Bravi
Bravi

Reputation: 773

Laravel hasMany with a filter

This is more like a recommendation of how to structure my database probably. Basically, I have a model App\Project and I have another model App\Asset.

App\Project hasMany App\Asset:

public function assets() {
   return $this->hasMany('App\Asset');
}

The assets are different images and the assets table has a type column.

So on the page where I actually display the project, what I want to do is to display an image that has original set as a type, as a starting / first image and then have others follow up. (all the assets are optional. not all the projects will have an original image.)

How can I achieve that? Should I filter an array and sort of cut the original out of an array?

Upvotes: 1

Views: 3508

Answers (2)

Cosmin Bacanu
Cosmin Bacanu

Reputation: 517

A less complicated method to achieve this might be just using a where clause on the relation:

public function assets() {
    return $this->hasMany('App\Asset')->where("type", "original");
}

Upvotes: 1

ffsantos92
ffsantos92

Reputation: 366

You can solve your problem with Query Scopes.

An example to get all assets with type as original:

Asset model:

use Illuminate\Database\Eloquent\Builder;

public function scopeOfOriginalType(Builder $query) {
    return $query->where('type', 'original');
}

Controller:

$project = Project::find(1);
$assets = $project->assets()->ofOriginalType()->get();

Upvotes: 3

Related Questions