Reputation: 334
My problem.
I have 2 laravel instances both are running at different IP's but the environment & versions are the same.
& I have 1 model which is related to other child models.
I want to pass the whole object over API and save it on the other end.
hope this clarify my issue.
Upvotes: 1
Views: 341
Reputation: 4813
To convert a model to JSON, you should use the toJson method. The toJson method is recursive, so all attributes and relations will be converted to JSON. You may also specify JSON encoding options supported by PHP:
//...
$users = App\User::with('posts')->all();
return $users->toJson();
//return $users->toJson(JSON_PRETTY_PRINT);
Then when it comes to consuming API you could fetch json already sent through data body raw request like
// First we fetch the Request instance
$request = Request::instance();
// Now we can get the content from it
$content = $request->getContent();
Upvotes: 1
Reputation: 2629
As far as I understand you, you can do it. here's a simple sneak peak:
$user = App\User::find(1);
return $user->toJson();
Which can be found here. Say you have a user model and you want to access this from outside. You can make an API endpoint (with authentication if required. however it is obviously recommended using secure authentication specially if your API endpoint access any model directly) which will accept a user ID and pass the whole user object over API response.
Upvotes: 1