Tharindu Thisarasinghe
Tharindu Thisarasinghe

Reputation: 3998

How to return complex objects in a Laravel API

I'm building a REST API using Laravel and wondering if there's a standard and accepted way (Framework or Package) to return complex collections as the response.

What I'm currently doing is, returning the object with json method,

public function show() {
    $ad = Ad::with('category')->get()->find($id);
    return Response::json($ad);
}

Or, just return the object where it automatically return as json

public function show() {
    $ad = Ad::with('category')->get()->find($id);
    return $ad;
}

This way is fine with the above method because relations are pre-contained before coveting to json. However, let's say I need to return the saved object just after store() is called. Like this...

public function store(SaveAdRequest $request){
        $ad = new Ad();
        $ad->title = $request->title;
        $ad->description = $request->description;
        $ad->category = $request->category;
        $ad->save();

        return $ad;
}

In above store() method, I have no direct way to get relations of the just saved object.

So, how to overcome this problem and is there a standard way of returning these complex objects rather than using json ?

Thanks!

Upvotes: 0

Views: 2093

Answers (2)

common sense
common sense

Reputation: 3912

There is no standard way for returning data from a REST API. You can return JSON, XML, HTML. Whatever suits you.

The common thing is that you have somehow serialize your (PHP) object before sending it over the wire. Recently JSON is used a lot because its light-weight, easy to process and readable by humans too.

A complex object is just another JSON object inside a JSON object.

Upvotes: 3

Etibar
Etibar

Reputation: 578

public function store(SaveAdRequest $request){
        $ad = new Ad();
        $ad->title = $request->title;
        $ad->description = $request->description;
        $ad->category = $request->category;
        $ad->save();

        $data = Ad::where('id', $ad->id)->with('category')->get();
        return Response::json($data );
}

Upvotes: 1

Related Questions