Clément Andraud
Clément Andraud

Reputation: 9279

Laravel response json useless array

I'm working on an API with Laravel and I have a problem with my json response, for example I have ina function :

    $company = Company::select('name')
        ->inRandomOrder()
        ->limit(1)
        ->get();

    return response()->json([
        'company' => $company,
    ]);

With this I get when I call my function :

{
    "company": [
        {
            "name": "Company Number 1"
        }
    ]
}

Why I have an array after company ? "company": [ Is there a way to return directly $company without an object before (named company in my example ?)

Thanks !

Upvotes: 0

Views: 1514

Answers (2)

spicydog
spicydog

Reputation: 1714

->get() returns Collection while first() returns the first object or the collection.

Therefore, limit(1) is no longer required, and the default action of Laravel is to response as JSON.

As a result, you can simply

return [
  'company' => Company::select('name')->inRandomOrder()->first()
];

Upvotes: 1

user1897253
user1897253

Reputation:

change your ->get() to ->first() so it returns the first model instead of a collection of models.

$company = Company::select('name')
    ->inRandomOrder()
    ->first();

return response()->json([
    'company' => $company,
]);

also ->limit(1) is probably unnecessary as first already does this.

Upvotes: 6

Related Questions