0

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 !

2
  • 2
    Try first method instead of get Commented Oct 12, 2016 at 13:43
  • Hum, good idea :p Commented Oct 12, 2016 at 13:44

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

->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()
];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.