0

I want to fetch all data from this table for that i am using query :

      $emp = Employee::where('user_id', '=', $user->id)->first();

    $holidays = Holiday::orderBy('holidays.id', 'desc')->take(5)->where('holidays.id', '=', $emp->id)->get();

It is not giving me any result. I am new to php can anyone help me out yrr?

Holiday Table

1
  • I think you want where('holidays.created_by', '=', $emp->id), because holidays.id should be unique, not tied back to the employee id. Commented Dec 14, 2021 at 13:25

1 Answer 1

3

The "eloquent" way to do it would be in your Employee model to set up the relationship between Employees and Holidays :

public function holidays() { 
    return $this->hasMany(Holiday::class);
}

and then in your Holiday model set up the reverse :

public function employee() { 
    return $this->belongsTo(Employee::class, 'created_by');
}

Note that we're having to pass over the name of the foreign key explicitly as it's not what Laravel is expecting (employee_id).

Then you can just load your Employee :

$emp = Employee::where('user_id', $user->id)->first();

and then access their holidays :

$holidays = $emp->holidays;

or :

$lastfiveholidays = $emp->holidays()->take(5);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.