Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

novichun's avatar

Laravel http API display in JSON

I got a task and I need your help. Firstly I would like to show you my App\Repositories\xyz.php:

public function getCars(): Collection
    {
return collect([
            new car(...),
            new car(...),
            new car(...),
        ]);
}

This is a collection.

There is a lot of data in it. And my task is that I have to use a Http Get Api endpoint to show ONE random Car from these in JSON format. I made a new controller file for this and the route for it but I don't know how can I continue it.

Thank you for your Reply!

0 likes
10 replies
tykus's avatar

There is not a lot of information to work with here; so this may not be the most appropriate approach...

Collection has a random method, so in your Controller, get the Collection from the repository and call random on it:

$randomCar = $this->repo->getBrokers()->random();

Assumes you have the repo resolved and available as an instance variable on the Controller...

1 like
novichun's avatar

@tykus I worked with this

public function index(){
        $repo = new CarRepository();
        $randomcar = $this->$repo->getCars()->random();
            dd($randomcar);
    }

But i got this error:

Object of class App\Repositories\CarRepository could not be converted to string

But i dont want to convert or anything, i would like to display in JSON format.

tykus's avatar

Object of class App\Repositories\CarRepository could not be converted to string

This suggests that you are attempting to echo the repo somewhere? $randomCar should give you one instance of the car class in the Collection; just use the $repo in scope rather than an instance variable:

public function index()
{
    $repo = new CarRepository();
    $randomcar = $repo->getCars()->random();
    dd($randomcar); // a car instance???
}
1 like
tykus's avatar

@novichun just re-read your code, the problem was here:

$this->$repo

Note the $ before repo.

1 like
novichun's avatar

@tykus I worked with this code:

 public function index(){
        $repo = new CarRepository();
        $randomcar = $repo->getCars()->random();
        return response()->json($randomcar);
    }

But i have to solve it with Http Get Api Endpoint. Whats that? :/

tykus's avatar

@novichun it is simply a Route definition mapped to that Controller action, I thought you had already done this, right?

I made a new controller file for this and the route

Route::get('random-car', [YourController::class, 'index']);
1 like
tykus's avatar
tykus
Best Answer
Level 104

@novichun In that case, you have a Http Get Api Endpoint

1 like

Please or to participate in this conversation.