dan3460's avatar

Selecting using test in model

On a model i have the following:

    public function granted()
    {
        if (Shares::where('albums_id', $this->id)
            ->where('users_id', Auth::user()->id)) {
            return true;
        } else {
            return false;
        }
    }

I'm trying to select albums where granted returns true but I'm blanking on how to do it. I wanted to write something like this:

    public function familyAlbums()
    {
        $albums = Albums::where($this->granted, true)->get();

        return view('albums.browse', compact('albums'));
    }

of course i'm getting an error. Can i do what i want to do?

0 likes
7 replies
Tray2's avatar

Not sure what it is you are trying to do but if you want the user only to see albums that that is shared with the user I would do something like.

$albums = Album::whereIn('id', Share::where('user_id', Auth::user()->id)->pluck('album_id')->toArray())->get();
dan3460's avatar

Thanks @tray2, your answer is pretty much what i have now. I thought that could be a more elegant solution using something like the granted function that i have. Maybe is not such a thing.

a4ashraf's avatar

Hello @dan3460

make sure your Album and Shares model. "hasOne"

and try this following code in your controller

$albums = Albums::with(['Shares', function($query){
                return $query->where('users_id', Auth::user()->id);
                }])->get();
dan3460's avatar

@a4ashraf thanks for that. The album model has a function hasmay() shares as the same album can be shared between many users. Don't understand the "hasOne" do you want me to create a function returning the relationship between the Album and the share?

a4ashraf's avatar

okay @dan3460

np if the Models has function HasMany(), but did you apply this following function


$albums = Albums::with(['Shares', function($query){
                return $query->where('users_id', Auth::user()->id);
    }])->get();
Tray2's avatar

You can always extract the Share::where to a function

protected function sharedAlbums()
{
    return Share::where('user_id', Auth::user()->id)->pluck('album_id')->toArray(); 
}

then call it like this

$albums = Album::whereIn('id', $this->sharedAlbums())->get();

Please or to participate in this conversation.