facing problem while trying to select specific columns from laravel relationship

59 Views Asked by At

My project runs on PHP 8.1.18 Laravel 9.52.7 that uses Mongodb driver (https://github.com/jenssegers/laravel-mongodb).

Project::with(['skills' => function($q) {$q->select('_id', 'name');}])->first();

The following is part of the exception I get:

enter image description here

1

There are 1 best solutions below

0
On

I see there r guys who Jump into just pulling down peoples reputation for asking questions. But anyway here is how I worked around the problem in case anyone faces the same:

The controller listing method:

/**
 * return project's index view
 */
public function index()
{
    $items = Project::where([])->with(['company', 'skills']);

    if (request()->all)
        return $this->select($items->limit(4)->get());

    $items = $items->paginate();

    $items_only = $items->getCollection();
    $res = $this->select($items_only);
    $items->setCollection($res);

    return response(['message' => 'success', 'data' => $items]);
}

The selecting method:

private function select($q)
{
    return $q->map(
        function ($q) {
            return [
                ...$q->only([
                    '_id',
                    'title',
                    'slug',
                    'featured_image',
                    'start_date',
                    'end_date',
                    'status',
                    'importance'
                ]),
                'company' => $q->company()->first(['name']),
                'skills' => $q->skills()->get(['name'])
            ];
        }
    );
}

NB: Anyone to kindly show me how to solve this better.