Return json from two classes in model - json

I'm trying to return json with two classes in my model
public function both()
{
return $this->belongsToMany(Car::class)->and(Driver::class)->withPivot('type'); // this is wrong
}
the reason I'm trying to get this like that is because in my function
public function check()
{
$user = JWTAuth::parseToken()->authenticate();
$id = $user->id;
$result = User::with('both')->where('id', $id)->get();
return response()->json($result);
}
right now in my model I have this
public function both()
{
return $this->belongsToMany(Car::class)->withPivot('type');
}
public function driver()
{
return $this->belongsToMany(Driver::class)->withPivot('type');
}
But the function returns json that has a different structure when both ends.
My question is can I have the function return a json with the same structure?
like this
[
{
"id": 4,
"name": null,
"phone": "9000",
"size_of_house": null,
"created_at": "2016-12-04 13:55:52",
"updated_at": "2017-03-08 14:03:44",
"deleted_at": null,
"both": [
{
"id": 177,
"name": "NIS",
"created_at": "2016-12-27 10:28:29",
"updated_at": "2016-12-27 10:28:29",
"pic": "http://localhost:8000/images/1482833485.jpg",
"pivot": {
"user_id": 4,
"car_id": 177,
"type": "car"
}
},
"both": [
{
"name": "Abdulaziz Alomhsen",
"age": "30",
"created_at": "2017-02-28 09:36:15",
"updated_at": "2017-03-08 08:46:06",
"status": "جايه",
"pic": "http://localhost:8000/images/1488714520.jpg",
"id": 2,
"pivot": {
"user_id": 4,
"driver_id": 2,
"type": "driver"
}
},

Related

Why JsonNode.get("key").asText() is returning empty String

I have a problem with saving to playersJson String, data from node "players". Node is created based on json dataJson, created with byte[] playesFile. I suspect that the error is due to incorrect parsing of these strings?
As a result, String playersJson returns an empty String and I would like it to contain information about "players" in json format, which I will then throw into Map<String,Player>
Code fragment:
byte[] playersFile = storageService.downloadFile(FILENAME);
String dataJson = new String(playersFile);
try {
JsonNode jsonNode = objectMapper.readTree(dataJson);
String playersJson = jsonNode.get("players").asText();
data = objectMapper.readValue(playersJson, new TypeReference<Map<String, Player>>(){});
} catch (JsonProcessingException e) {
e.printStackTrace();
}
String dataJson:
{
"players":
[
{
"key": "03a2452c-9d6b-47f5-9616-9a6833312762",
"value": {
"uuid": "2ae8d022-e0f4-4502-8e0e-1874997543e3",
"name": "Artur",
"elo": 2000,
"gamesPlayed": 0,
"email": "arti123i#mail.com"
}
},
{
"key": "8526db7c-6930-45bf-9ae1-fb93e97ff4ba",
"value": {
"uuid": "1bb43d73-3f94-40fc-a680-99f4a9304001",
"name": "Kamil",
"elo": 2000,
"gamesPlayed": 0,
"email": "kamil223#mail.com"
}
},
{
"key": "5a65ba8c-2180-464b-afe4-69c29b785282",
"value": {
"uuid": "b3dc8c98-5759-433e-88cd-0233946b9241",
"name": "Marek",
"elo": 3000,
"gamesPlayed": 0,
"email": "marek111#mail.com"
}
}
],
"games":
[
{
"reportedTime": "2022-07-11T14:43:10.0354202+02:00",
"reportedBy": {
"uuid": "2ae8d022-e0f4-4502-8e0e-1874997543e3",
"name": "Artur",
"elo": 2016,
"gamesPlayed": 1,
"email": "arti123i#mail.com"
},
"result": [
[
{
"player": {
"uuid": "2ae8d022-e0f4-4502-8e0e-1874997543e3",
"name": "Artur",
"elo": 2016,
"gamesPlayed": 1,
"email": "arti123i#mail.com"
},
"eloBefore": 2000,
"eloAfter": 2016
},
{
"player": {
"uuid": "1bb43d73-3f94-40fc-a680-99f4a9304001",
"name": "Kamil",
"elo": 2016,
"gamesPlayed": 1,
"email": "kamil223#mail.com"
},
"eloBefore": 2000,
"eloAfter": 2016
}
],
[
{
"player": {
"uuid": "b3dc8c98-5759-433e-88cd-0233946b9241",
"name": "Marek",
"elo": 2968,
"gamesPlayed": 1,
"email": "marek111#mail.com"
},
"eloBefore": 3000,
"eloAfter": 2968
}
]
]
}
]
}
code image
code debugging

Pagination not working while retriving data with costom json function

I'm fetching data to paginate but pagination is not working, the fetch response is added below, if I return the query relation it retrieves correct data but when I pass it to the custom response function it fetch data only but not the pagination links
try {
$type = 'success';
$status_code = 200;
$message = 'Posts data listed.';
$response = PostResource::collection(Post::with(['associate:id,name,avatar', 'comments:id,commenter_id,commentable_id,comment,created_at'])
->latest('posts.created_at')
->paginate(2));
} catch (Exception $e) {
$type = 'error';
$status_code = $e->getCode();
$message = $e->getMessage();
$response = false;
}
return response_data($type, $status_code, $message, $response);
Here is my response_data function code
function response_data($type, $status, $message = false, $response)
{
return response()->json(['type' => $type, 'status' => $status, 'message' => $message, 'response' => $response]);
}
but if return the query directly it retrieves data with pagination
here is my response that retrieved by the collection
{
"type": "success",
"status": 200,
"message": "Posts data listed.",
"response": [
{
"id": 32,
"associate_id": 5,
"title": "Test Title",
"content": "Post descriptuoin",
"image": "https://oppazz.oppazzgiftcode.com/images/posts/1632472717.Laravel.png",
"created_at": "2 months ago",
"associate": {
"name": "Code Logic Technologies Pvt. Ltd.",
"avatar": "https://oppazz.oppazzgiftcode.com/images/associates/1633002782_logo.png"
},
"comments": [
{
"id": 13,
"commenter_id": "62",
"commentable_id": "32",
"comment": "Nice offer",
"created_at": "2 months ago",
"user": {
"id": 62,
"name": "Rikesh Shakya",
"username": "rikesh-shakya",
"mobile_number": "9823783191",
"email": "skybks5#gmail.com",
"provider_id": null,
"avatar": "https://oppazz.oppazzgiftcode.com/images/logo.png",
"email_verified_at": null,
"status": "Y",
"created_at": "2021-06-11T18:05:07.000000Z",
"updated_at": "2021-06-11T18:05:07.000000Z",
"created_by": null,
"updated_by": null,
"device_type": null
}
},
{
"id": 16,
"commenter_id": "88",
"commentable_id": "32",
"comment": "tetetete",
"created_at": "2 months ago",
"user": {
"id": 88,
"name": "Neelam Kera",
"username": "neelam-ranjitkar",
"mobile_number": "9860322060",
"email": "shresthaneelam19#gmail.com",
"provider_id": null,
"avatar": "https://oppazz.oppazzgiftcode.com/images/logo.png",
"email_verified_at": null,
"status": "Y",
"created_at": "2021-07-15T14:08:21.000000Z",
"updated_at": "2021-07-15T14:08:21.000000Z",
"created_by": null,
"updated_by": null,
"device_type": null
}
}
],
"associate_social_sites": {
"id": 5,
"associate_id": 5,
"facebook": "https://www.fachook.com",
"instagram": "https://www.instagram.com",
"twitter": "https://www.twitter.com",
"status": "Y",
"created_at": null,
"updated_at": "2021-09-24T09:29:57.000000Z",
"created_by": null,
"updated_by": null,
"device_type": null
}
},
{
"id": 31,
"associate_id": 9,
"title": "OppazZ Coffee For Happiness (Giveaway series)",
"content": "OppazZ",
"image": "https://oppazz.oppazzgiftcode.com/images/posts/1632367205.kamloops-art-page-2.jpg",
"created_at": "2 months ago",
"associate": {
"name": "OppazZ",
"avatar": "https://oppazz.oppazzgiftcode.com/images/associates/1622551849_184399208_2242958835839866_1824735327179728878_n.jpg"
},
"comments": [],
"associate_social_sites": null
}
]
}
how can it be resolved and fetch pagination link along with the data fetched above
The Laravel paginator result classes implement the Illuminate\Contracts\Support\Jsonable interface contract and expose the toJson method, so it's very easy to convert your pagination results to JSON.
You may also convert a paginator instance to JSON by simply returning it from a route or controller action:
https://laravel.com/docs/5.3/pagination#converting-results-to-json

Convert two dimentional array into the json object in Laravel

I am converting a two-dimensional array into a JSON object.
Now my controller returning this output:
[
[
{
"id": 1,
"title": "V1",
"project_id": 1
}
],
[]
]
Want to convert it like:
[
{
"id": 1,
"name": "Laravel"
},
{
"id": 2,
"name": "Wordpress"
}
]
My controller code:
$user = auth()->user();
$projectVersions = array();
foreach($user->projects as $project)
{
$projectId = $project->pivot->project_id;
$projectVersions[] = Version::where('project_id', $projectId)
->where('created_by', $user->id)
->get();
}
return $projectVersions;
When I am using below code which is suggested by #John Lobo, it is returning below output:
{
"id": 2,
"name": "Hadayat Niazi",
"email": "niazicr801#gmail.com",
"is_admin": 0,
"email_verified_at": null,
"created_at": "2021-06-11T15:13:00.000000Z",
"updated_at": "2021-06-11T15:13:00.000000Z",
"projects": [
{
"id": 1,
"name": "Laravel",
"pivot": {
"user_id": 2,
"project_id": 1
},
"versions": [
{
"id": 1,
"title": "V1"
}
]
}
]
}
Displaying the user projects and versions:
Again I am updating the code for #John Lobo, he want to look the output
$user = User::with(['projects', 'projects.versions'])
->find(auth()->user()->id);
$result = $user->projects->map(function ($project) {
return [
$project->versions,
];
});
return $result;
Output the code
[
[
[
{
"id": 1,
"title": "V1",
"project_id": 1,
"version": "1.22",
"created_by": 2,
"is_publish": 0,
"feature": "<b>In this ipdate asdsdasd</b>",
"bug_fix": "<p><b>sdfdffffffffff</b></p>",
"created_at": "2021-06-12T08:08:21.000000Z",
"updated_at": "2021-06-12T08:08:21.000000Z"
},
{
"id": 2,
"title": "v2",
"project_id": 1,
"version": "2.12",
"created_by": 2,
"is_publish": 0,
"feature": "adsdasdsadas",
"bug_fix": "sddasdas",
"created_at": null,
"updated_at": null
}
]
],
[
[]
]
]
In controller you can do the following.if you have relation in project model called version
$projectVersions=User::with(['projects','projects.version'])->find(auth()->user()->id);
return $projectVersions->projects;
I believe Project model has below relationship
public function version(){
return $this->hasMany(Version::class);
}
Updated
$user=User::with(['projects','projects.versions'])->find(auth()->user()->id);
$result = $user->projects->map(function ($project) {
return $project->versions;
});
dd($result);
Use like below
$json = json_encode($responseOfController);
echo "<pre>";print_r($json);die;

unable to get desired json format while creating laravel 5 api

i have the following Template model and TestCategory hasMany Test:
class Template extends Model
{
protected $table = 'test_templates';
protected $fillable = [
'customers_id',
'tests_categories_id',
'tests_id'
];
public function customers(){
return $this->belongsTo(Customer::class, 'customers_id');
}
public function testCategories(){
return $this->belongsTo(TestCategory::class, 'tests_categories_id');
}
public function tests(){
return $this->belongsTo(Test::class, 'tests_id');
}
}
And I have the following index method defined in TemplateController
public function index($customerId)
{
$templates = Template::with( 'customers','testCategories','tests')
->where('customers_id', $customerId)->get();
$templates = $templates->groupBy('tests_categories_id');
$templates = json_decode($templates, true);
$templates = array_values($templates);
return response()->json(['Status' => True, 'template' => $templates]);
}
I got the following json output:
{
"Status": true,
"template": [
[
{
"id": 1,
"customers_id": 1,
"tests_categories_id": 1,
"tests_id": 1,
"created_at": "2018-09-10 11:03:44",
"updated_at": "2018-09-10 11:03:44",
"customers": {
"id": 1,
"name": "Queen PVT.Ltd",
"address": "gotham",
"contact_number": "9842********",
"created_at": "2018-09-10 11:03:43",
"updated_at": "2018-09-10 11:03:43"
},
"test_categories": {
"id": 1,
"name": "General Tests",
"created_at": null,
"updated_at": null
},
"tests": {
"id": 1,
"tests_category_id": 1,
"name": "Lamination",
"created_at": null,
"updated_at": null
}
},
{
"id": 2,
"customers_id": 1,
"tests_categories_id": 1,
"tests_id": 2,
"created_at": "2018-09-10 11:03:44",
"updated_at": "2018-09-10 11:03:44",
"customers": {
"id": 1,
"name": "Queen PVT.Ltd",
"address": "gotham",
"contact_number": "984*******",
"created_at": "2018-09-10 11:03:43",
"updated_at": "2018-09-10 11:03:43"
},
"test_categories": {
"id": 1,
"name": "General Tests",
"created_at": null,
"updated_at": null
},
"tests": {
"id": 2,
"tests_category_id": 1,
"name": "Paper Type",
"created_at": null,
"updated_at": null
}
}
],
[
{
"id": 7,
"customers_id": 1,
"tests_categories_id": 2,
"tests_id": 8,
"created_at": "2018-09-10 11:03:44",
"updated_at": "2018-09-10 11:03:44",
"customers": {
"id": 1,
"name": "Queen PVT.Ltd",
"address": "gotham",
"contact_number": "984******",
"created_at": "2018-09-10 11:03:43",
"updated_at": "2018-09-10 11:03:43"
},
"test_categories": {
"id": 2,
"name": "Scratch Test",
"created_at": null,
"updated_at": null
},
"tests": {
"id": 8,
"tests_category_id": 2,
"name": "HRN Visibility",
"created_at": null,
"updated_at": null
}
}
]
]
}
I want to collect all the tests as per the test_categories without reprinting customers and test_categories as following:
{
"Status": true,
"template": [
[
{
"id": 1,
"customers_id": 1,
"tests_categories_id": 1,
"tests_id": 1,
"created_at": "2018-09-10 11:03:44",
"updated_at": "2018-09-10 11:03:44",
"customers": {
"id": 1,
"name": "Queen PVT.Ltd",
"address": "gotham",
"contact_number": "984*****",
"created_at": "2018-09-10 11:03:43",
"updated_at": "2018-09-10 11:03:43"
},
"test_categories": {
"id": 1,
"name": "General Tests",
"created_at": null,
"updated_at": null
},
"tests": {
{
"id": 1,
"tests_category_id": 1,
"name": "Lamination",
"created_at": null,
"updated_at": null
},
{
"id": 2,
"tests_category_id": 1,
"name": "Paper Type",
"created_at": null,
"updated_at": null
}
}
}
],
[
{
"id": 7,
"customers_id": 1,
"tests_categories_id": 2,
"tests_id": 8,
"created_at": "2018-09-10 11:03:44",
"updated_at": "2018-09-10 11:03:44",
"customers": {
"id": 1,
"name": "Queen PVT.Ltd",
"address": "gotham",
"contact_number": "984265*****",
"created_at": "2018-09-10 11:03:43",
"updated_at": "2018-09-10 11:03:43"
},
"test_categories": {
"id": 2,
"name": "Scratch Test",
"created_at": null,
"updated_at": null
},
"tests": {
{
"id": 8,
"tests_category_id": 2,
"name": "HRN Visibility",
"created_at": null,
"updated_at": null
}
}
}
]
]
}
If I understand the problem correctly the tests are being separated into different templates when you are expecting some of them to be related to the same template.
This is because your Template class is storing the test_id that it belongs to and it can only store 1 test per Template. So when you are calling Template::with('tests') it can only return one Test::class.
Because you expect to see that many Tests belongTo one Template, and when you look at the relationship from the Template to Test, you expect that a Template has many Tests. Therefore, your Template class should implement the hasMany relationship like so:
class Template extends Model
{
protected $fillable = [
'customers_id',
'tests_categories_id' // notice the removal of the test_id which should also be removed from the test_templates migration
];
...
public function tests(){
return $this->hasMany(Test::class); //change belongsTo to hasMany
}
...
}
Instead of storing the test_id on the Template class you should be storing the template_id on your Test class and look something like so:
class Test extends Model
{
protected $fillable = [
...
'test_template_id' // This should be added to $fillable and the tests migration
...
];
...
public function template(){
return $this->belongsTo(Template::class, test_template_id);
}
...
}
Now when you call Template::with('tests') it can return many Test::class and should match your expected output.

Formatting Laravel JSON Object with relations

My goal is to output JSON for an API like this:
[
{
"id": 3,
"name": "QUbkaUJhNm",
"email": "w6KYFZnypT#gmail.com",
"created_at": null,
"updated_at": null,
"profile": {
"a": "value",
"b": "value",
"c": "value"
}
},
{
"id": 5,
"name": "lYXmtkKuX9",
"email": "yu3dob2lyH#gmail.com",
"created_at": null,
"updated_at": null,
"profile": {
"a": "value",
"b": "value",
"c": "value"
}
}
]
I have two models.
The User Model:
public function profile()
{
return $this->hasOne(Profile::class);
}
The Profile Model:
public function user()
{
return $this->belongsTo(User::class);
}
What should the code for my APIcontroller be?
$users = User::all();
...
Thank you!
You can use Eager Loading like this:
return User::with('profile')->get();
if you want the result paginate
return User::with('profile')->paginate();