PrashanD
PrashanD

Reputation: 2764

Laravel - Trying to get property on a non-object

I'm attempting to create a simple data display form in Laravel to display contact details given phone number. Phone number is passed in to the form from the URL (route). If the URL is does not include a phone number all the fields of the form should be empty string. To achieve this I just check if the URL is called without a phone number ($number) and if so, create an associative array with the correct keys and empty strings as values

class InboundCallController
{
    public function inboundCall($number=null){
        if($number==null) {
            $contact=array(
                "id"=>"",
                "registration_no"=>"",
                "title"=>"",
                "firstname"=>"",
                "lastname"=>"",
                "primary_contact"=>"",
                "secondary_contact"=>"",
                "email"=>"",
                "gender"=>"",
                "address_line1"=>"",
                "address_line2"=>"",
                "city_state_province"=>"",
                "zip"=>"",
                "country"=>"");

            return view('InboundCall')
                ->with('number',null)
                ->with('contact',$contact);
        }

        $contact=$this->retrieveContact($number);

        return view('InboundCall')
            ->with('number',$number)        //CLI passed from soft-phone
            ->with('contact',$contact)    //Contact details retrieved from db
    }

    private function retrieveContact($number){
        return DB::table('contacts')    //Retrieve contact
            ->where('primary_contact',$number)
            ->first();
    }

}

Trying to get property of non-object (View: /var/www/html/csp/resources/views/InboundCall.blade.php)

On line 37 of the blade I have this:

value="{{$contact->primary_contact}}"

Upvotes: 0

Views: 5629

Answers (2)

Daniel Bejan
Daniel Bejan

Reputation: 1468

That's the idea.. If $number is null then you send an associative array to the view, which is not of type object.. It's an array so you can't access the values via ->.. Try accessing the data like this instead in the view, add @ to void promoting error, when $contact is null

value="{{ @$contact['primary_contact'] }}" 

EDIT(for others in the same trouble):

You might also want to consider not sending an object if you have $number and an array otherwise.. You might send a new Contact where Contact is the name of the model and maybe initialize the fields of Contact as empty or make a static method Contact::emptyContact that returns an object of type Contact so you don't have to check the type of data inside the view

Upvotes: 3

Masud Miah
Masud Miah

Reputation: 256

value="{{$contact->primary_contact}}"

here $contact is an array not object use it like this

value="{{$contact['primary_contact']}}"

Upvotes: 1

Related Questions