Search code examples
laravellaravel-artisan

Retrieve related table and select fields from primary table using Laravel Artisan


In the following code, The Users table has a related table phoneNumbers. When I retrieve a list of all users like this,

return Person::with('phoneNumbers')->get();

everything works fine. However, when I attempt to specify a list of columns to return from the Person table, the phone_number returns empty.

 return Person::with('phoneNumbers')
          ->get(['fname','lname', 'email']);

If I add the number field or phone_number.number to the get array, then I get an error as an undefined column. What is the laravel way of handling this.


Solution

  • Try this:

    return Person::select(['your_foreign_key', 'fname','lname', 'email'])
    ->with('phoneNumbers')get();