jbowman99
2 years ago

return Models based upon pivot table data

Posted 2 years ago by jbowman99

I have a user model and customer model with a pivot table customer_user table. I want to fetch all customers that a user has attached within a specific span of time.

I was going to fetch all of the customer_user entries where the created_at date fell between a specific date range. then for each over the results and build a collection with that data:

$recent = DB::table('customer_user')
            ->where('user_id', $this->id)
            ->where('created_at', '>=', $start_week)
            ->where('created_at', '<=', $end_week)
            ->get();

foreach($recent as $new_customer){
    //create customer collection based of of the id's here
}

return //that collection

is there an easier way? can i add withPivot created_at to the relationship and find this same collection that way?

Please sign in or create an account to participate in this conversation.