0

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!

2 Answers 2

3

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.

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

Comments

1
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 );
}

2 Comments

Thanks. Your answer just fixed my problem . Anyway, I'm still looking for an answer about a standard and accepted way of returning data.
did you check $ad['category'] = $ad->category(); return Response::json($ad); ?

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.