Smsma's avatar
Level 2

react.js with laravel relationship

this error happend when I add

{client.company.name} in view

Uncaught TypeError: Cannot read property 'name' of null

in CompanyController

public function index(request $request)
    {
       
        $clients = $this->client->with('company')->orderBy('date_created','DESC');
       
        if($request->search){
            $clients = $clients->where(function($query) use($request){          
                $query->where('client_id', $request->search);
                $query->orWhere('first_name', 'LIKE', '%' . $request->search . '%');
                $query->orWhere('contact_phone',$request->search);
            });
        }
        // applay pagination on clients list
        $clients = $clients->paginate(10);
        // get all clients 
        return response()->json($clients);
    }

 constructor(props)
    {
        super(props);
        this.state={
            loading : true,
            clients:[],
            search    : '',
            page      : 1,
            total     : 0,
            pageCount : 0,
        };
        this.handleChangeSearch   = this.handleChangeSearch.bind(this);
        this.handleSubmit         = this.handleSubmit.bind(this);
        this.handlePageChange     = this.handlePageChange.bind(this);
    }

in render()

<tbody>
                                                {
                                                    this.state.clients.map(function(client, i){
                                                        return(
                                                            <tr key={i}>
                                                                <td><Link to={`/clients/${client.client_id}`}>{client.client_id}</Link></td>
                                                                <td>{client.name }</td>
                                                                <td>{client.email_address }</td>
                                                                <td>{client.contact_phone }</td>
                                                                <td>{client.date_created }</td>
                                                                <td>{client.company.name}</td>
                                                            </tr> 
                                                        );
                                                    })
                                                }
                                                
                                            </tbody>

client.php

 public function company(){
        return $this->belongsTo(Company::class, 'company_id');
    }

company.php

public function clients(){
        return $this->hasMany(Client::class, 'company_id');
    }

0 likes
2 replies
marktimbol's avatar

Might be the one of the client doesn't have a company?

Please or to participate in this conversation.