Mendizalea
Mendizalea

Reputation: 53

Laravel pagination with relation

This is the code that I have:

public function divisions(Request $request)
{
    $q = $request->get('q');

    return Division::where('name', 'like', "%$q%")
            ->with(['nation' => function($query) {
                $query->select('id', 'name');

            }])->simplePaginate();
}

And return the following:

{
    "id": 1,
    "name": "1",
    "classify": 1,
    "nation_id": 1,
    "user_id": 1,
    "created_at": "2019-05-08 09:00:00",
    "updated_at": "2019-05-08 09:00:00",
    "nation": {
        "id": 1,
        "name": "France"
    }
}

But I need the following. What can I do to only return the following?

{
    "id": 1,
    "name": "1",
    "nation": "France"
}

Thanks

Upvotes: 1

Views: 210

Answers (2)

Priyanka khullar
Priyanka khullar

Reputation: 517

Try below given answer I think that will help you to achieve your problem solution.

Solution 1:

public function divisions(Request $request)
{
    $string = $request->get('q');
    $builder = new Division;
    $builder->where('name', LIKE, "%$string%")
            ->with(['nation' => function($query) {
                $query->select('id', 'name');
            }]);

    $result = $builder->selectRaw("id, name, nation.name as nation")->simplePaginate();

    return response()->json($result);
}

Solution 2

In Controller

public function divisions(Request $request)
{
    $string = $request->get('q');
    $builder = new Division;
    $builder->where('name', LIKE, "%$string%")
            ->with(['nation' => function($query) {
                $query->select('id', 'name');
            }]);

    $paginator = $builder->paginate();

    $data = fractal()
                ->collection($paginator->getCollection(), new DivisionsTransformer, 'divisions')
                ->serializeWith(new DataArraySerializer())
                ->paginateWith(new IlluminatePaginatorAdapter($paginator))
                ->toArray();
}

DivisionsTransformers

public function transform($resource)
{
    return [
        'id' => $resource->id,
        'name' => $resource->name,
        'nation' => $resource->nation->name,

    ];
}

Here is the reference of transformers library. https://github.com/spatie/laravel-fractal

Upvotes: 0

Khawlah Elshah
Khawlah Elshah

Reputation: 144

If you are using it to build an API, you can use Eloquent API Resources, so can use it as the following:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'nation' => $this->nation->name,
    ];
}

Upvotes: 1

Related Questions