Wednesday, March 15, 2017

Laravel Elquent filter is ignored when returning results

I am trying to return a (JSON) string of a specific user with his/her posts. However the Post model contains several columns that aren't of interest for API implementations and I want to exclude these columns from the result.

Why does the following still return every column in the Posts relation? I've tried multiple ways of retrieving specific columns on the Post model.

$result = User::with([
    'posts' => function($q) {
        $q->addSelect('title', 'tag');
    }])
    ->where(['api' => 1, 'id' => $id])
    ->first(['id', 'username', 'role']);

return $result;

dumping

$q->get()

shows exactly what I want, however the returned $result includes all columns of the Post model anyway.

My Laravel version is 5.2



via Chris Hessler

Advertisement