Raj
Raj

Reputation: 2028

Select specific columns of table and relation in laravel

Lets consider I have a Model User and another Model Employee

Now I want to pluck only some fields of Employee model such as salary, id, emp_id along with some columns of User model such as name,id.

$employee = Employee::with('user:id,name')
             ->where('department', $request->department)
             ->get(['id', 'emp_id', 'salary']);

When I execute this it will return id,emp_id,salary data but for user:name,id it will return null

How can I also specify user:id,name in get() ?

Upvotes: 0

Views: 1020

Answers (2)

Namoshek
Namoshek

Reputation: 6544

You can either load the full model or only some fields of it. To only load some fields, use select(). It also works within the relationship eager loading query:

$employees = Employee::with(['user' => function ($query) {
        $query->select(['id', 'employee_id', 'name']);
    }])
    ->where('department', $request->department)
    ->select(['id', 'emp_id', 'salary'])
    ->get();

Upvotes: 2

TalESid
TalESid

Reputation: 2514

use select() method from Query bulider:

$employee = Employee::with('user')   // or users <---
                    ->select(['id', 'emp_id', 'salary', 'users.id AS user_id', 'users.name AS username'])
                    ->where('department', $request->department)
                    ->get();

Upvotes: 0

Related Questions