Gonzalo F S
Gonzalo F S

Reputation: 408

How could I get only specified columns instead of the full object? Laravel Eloquent

this is my first time asking something here and I hope I do it alright. Im new to Laravel and I just know the basics of Eloquent, what I am trying to do is a game recommendator, so, in order to do so, the user sets a genre and I want to return all the games with this genre.

I am using whereHas as I am using a many to many relationship, this is my code:

public function searchByPreferences(){
    $genre_id = request('genre');
    $games = Game::whereHas('genres', function (Builder $query) use($genre_id) {
                $query->where('genre_id',$genre_id);
            })->get();

    dd($games);
}

So, this returns the games with all their data, and what I want is to only get an array of their IDs so I can make the petition of the game by id later. Thank you in andvance!

Upvotes: 0

Views: 183

Answers (2)

Rajesh Lalvadiya
Rajesh Lalvadiya

Reputation: 36

You should use pluck() function to get list of ids as below :

public function searchByPreferences(){
            $genre_id = request('genre');
            $games = Game::whereHas('genres', function (Builder $query) use($genre_id) {
                        $query->where('genre_id',$genre_id);

                    })->pluck('id')->all();

            dd($games);
        }

Upvotes: 2

Gonzalo F S
Gonzalo F S

Reputation: 408

I just found the solution and it's pretty easy.

You can specify the column giving the get() a parameter like this:

    public function searchByPreferences(){
    $genre_id = request('genre');
    $games = Game::whereHas('genres', function (Builder $query) use($genre_id) {
                $query->where('genre_id',$genre_id);

            })->get('id');

    dd($games);
}

Upvotes: 1

Related Questions