Laravel return relationship object with data from pivot table

I have the following tables setup in my application:

  • user
  • job_title
  • job_title_user (pivot table)

I have setup a relationship model for job titles in the user model, like so:

/**
 * The job titles that belong to the user.
 *
 * @return Object
 */
public function jobTitles()
{
    return $this->belongsToMany('App\Models\User\JobTitle');
}

I want to be able to select multiple rows from the user table, whilst joining on the job_title_id field from the job_title_user table.

So basically i’m looking to do a select on the user table (selecting multiple users), but also select which job titles the user has assigned to them.

The other problem is that I want to send the returned data to jSon, like this:

    return response()->json([
        'rows'    => $rows
    ]);

How can I achieve this?

Thanks!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s