How can I add default framework / conditions for relationships in Laravel 5?

So, I have a table called files, which contains a list of files with their corresponding name, path and file type. Then I have a few other tables to which you can attach files. For example, a table user_profiles. And finally, I have a pivot table for multi-user polymorphic communication between files and other tables. The pivot table is called fileables(could not come up with a better name). Users can now have several images attached to their profile, and possibly several videos that both come from files.

Usually, if these were just images, I would do something like this:

class UserProfile extends Model {

    public function images()
    {
        return $this->morphToMany('App\File', 'fileable');
    }

}

However, since these are images and videos, I would like to do something like this:

class UserProfile extends Model {

    public function images()
    {
        return $this->morphToMany('App\File', 'fileable')->where('type', 'LIKE', 'image%');
    }

    public function videos()
    {
        return $this->morphToMany('App\File', 'fileable')->where('type', 'LIKE', 'video%');
    }

}

But that does not work. So what is the right way to do this?

+4
source share
1 answer

I would create areas in your model File:

public function scopeImages($query)
{
    return $query->where('type', 'LIKE', 'image/%');
}

public function scopeVideos($query)
{
    return $query->where('type', 'LIKE', 'video/%');
}

And then use the ones that are in your model UserProfile:

public function images()
{
    return $this->morphToMany('App\File', 'fileable')->images();
}

public function videos()
{
    return $this->morphToMany('App\File', 'fileable')->videos();
}
+4
source