Wednesday, March 8, 2017

Return json from two classes in model

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"
    }
  },



via leo0019

Advertisement