Question

I have an Eloquent structured query like this: Ex.

public function showUserWithFriends($username){
   $user = User::where('name','=',$username)->with('friends','friends.jobs')->get()->first();
   return $user;
}

This is Query with User, certain username, with his friends and with his friends jobs. But my friends.jobs are json_decoded in SQL database. Is there any fancy way to decode it in Model, or should I go to Blade and do the work there?

EDIT:
Code Output:

{ 
 'username': 'john.eager',
 'firstname': 'John',
 'lastname: 'Eager'
 'friends': [
     {
       'firstname': 'Marco',
       'lastname': 'Polo',
       'jobs':[
           {
            'data': "{\"1\":\"Software Inc\",\"2\":\"Programmer\",\"3\":\"Salary Great\",\"4\":\"Holiday No\"}"
            }
       ]
     },
     {
       'firstname': 'Dragon',
       'lastname': 'Slayer',
       'jobs':[
           {
            'data': "{\"1\":\"Software Inc\",\"2\":\"Programmer\",\"3\":\"Salary Great\",\"4\":\"Holiday No\"}"
            }
       ]
     }
  ]
}
Was it helpful?

Solution

since you work with eloquent you could do the processing in your model and never worry about it. you could also provide a method to do the opposite: to save from a array of jobs to json for the database.

class Job extends Eloquent
{
    /**
     * will be executed as soon as you call $job->jobs
     *
     * @return array
    public function getData()
    {
        $data = json_decode($this->jobs);
        return $data;
    }
}

this works with any property. so if you have my_pretty_long_attribute would be public function getMyPrettyLongAttribute().

with your example

@foreach ($user->friends as $friends)
    @foreach ($friends->jobs as $job)
        $job->data // <- this will be your [1: "Software Inc", 2: "Programmer", ...] array
    @endforeach
@endforeach
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top