Eden WebStudio
Eden WebStudio

Reputation: 788

Call to member function on NULL in Laravel PhP

I have the below error. The client model has a relationship with the appointments model. When I replace variable $client with their id (1), it successfully returns a collection of appointments. But with the variable it returns NULL. I am trying to loop through each client's appointment to work out the duration total. My error is that i can't retrieve appointments when using $client variable from previous for each loop.

FYI the foreach $clients as $client loop returns a collection of all clients.

Call to a member function appointments() on null

public function autoGenerate(Request $request) {

    $date1       =  $request->input('date_from');
    $date2       =  $request->input('date_to'); 
    $customer    = $request->input('customer_account');

    if(count($customer) > 0)
    {       
        $clients     = Customer::find($customer)->client()->get();

        foreach($clients as $client)
            { 
                $appointments = Client::find($clients)->appointments()->get();

                    foreach($appointments as $appointment)
                    {       
                        //other code            
                    }               
            }

        //other code


    }
    $invoices = Invoice::all();
    return redirect('invoice');
}

Upvotes: 1

Views: 5014

Answers (1)

Dekel
Dekel

Reputation: 62676

I'm not sure how your $client variable is built, but you should probably use

$appointments = Client::find($client)->appointments()->get();

Or

$appointments = Client::find($client->id)->appointments()->get();

Note in my first example the usage of $client instead of $clients.

Upvotes: 2

Related Questions