In Our previous tutorial we have seen how to generate customized Json data in which we had generated 2 field values from
Usertabel of database.
__Now, Assuming Requirement: I need a json data of User Table along with below aditional data like
- Virsion
- attribution
- valid_as_of
- If i need
Virsion,attributionandvalid_as_of, attribiutes in my Json Object. what would i do then...
__We will add with(){} function with additional data in our User class as shown below:
- Lets see where i will make Changes in code.
NOte: Make sure you have Resourec folder with User class under
<Your-app>\app\http\Resources
+Change the content of above file as shown below.
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
use Illuminate\Support\Facades\Log;
class User extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'name' => $this->name,
'email' => $this->email,
'profile' => url('/user/'. $this->id . '/'),
];
}
public function with($request){
return [
'version' => '2.0.0',
'attribution' => url('/terms-of-service'),
'valid_as_of' => date('D, d M Y H:i:s'),
];
}
}
<?php
use App\User;
use App\Http\Resources\User as UserResource;
Route::get('/', function () {
return view('welcome');
});
Route::get('/json', function () {
$users = User::first();
return new UserResource($users);
});- Here my Application is
'demo-app'and its virtual host url ishttp://demo-app/. So i will open browser and hit:http://demo-app/jsonand see tha magic of LARAVEL RESOURCES
