0

I am using laravel excel to export my data. Inside map function, the $credit and $debit variables but when returning them, it throws a error.

The error is :

Trying to get property 'name' of non-object

here is my map function:

public function map($partner): array
{
    $credit = Bank::whereId($partner->credit)->first(); // also used: Bank::find($partner->credit);
    $debit = Bank::whereId($partner->debit)->first();
    dd($credit->name) // returns 'test'

    return [
        $partner->full_name, // this returns correctly.
        $credit->name, // returns "Trying to get property 'name' of non-object"
                       // if use $credit, it returns whole credit object.
        $debit->name,  // returns "Trying to get property 'name' of non-object"
                       // if use $credit, it returns whole debit object.
    ];
}

1 Answer 1

1

Look like few $partner has no credit or debit so check null condition

public function map($partner): array
{
    $credit = Bank::whereId($partner->credit)->first(); Bank::find($partner->credit);
    $debit = Bank::whereId($partner->debit)->first();
   

    return [
        $partner->full_name, 
        $credit->name??null,
        $debit->name??null,          
    ];
}

Also you can do

$data=[$partner->full_name];
isset($credit->name)? array_push($data,$credit->name)?null;
isset($debit->name)? array_push($data,$debit->name)?null;
  
return $data;
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks John Lobo, The issue is that: $credit->name isn't null, It does exists. it does exists inside the function and I dumped it. but it does not return it
@MahdiJafari have you checked for all records ? since dd($credit->name) will check for only one record
Not yet. Let me check it

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.