skip to Main Content

little by little but right now I have this error "Attempt to read property "name" on null" and in my database I have the information so that it has to appear in my view, please help my database data is full and my cities and countries are all well organized and it still gives me the error when calling a data from the cities_id source table

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="cssapp.css">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <title>prueba</title>
</head>
<body>
    <div class="tittle">
        <h1>hola</h1>
    </div>
    <table class="table">
        <thead>
            <tr>
                <th scope="col">id</th>
                <th scope="col">nombre</th>
                <th scope="col">correo</th>
                <th scope="col">ciudad</th>
                <th scope="col">pais</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($users as $user)
            <tr>
                <td>{{$user->id}}</td>
                <td>{{$user->name}}</td>
                <td>{{$user->email}}</td>
                <td>{{$user->city->name}}</td>
                <td>{{$user->city && $user->city->country ? $user->city->country->name : 'N/A'}}</td>
            </tr> 
            @endforeach
        </tbody>
    </table>
    
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
</body>
</html>

the view

the models

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use AppModelsUser;
use AppModelsCountry;

class City extends Model
{
    use HasFactory;

    public function User()
    {
        return $this->hasMany(User::class);
    }

    public function country()
    {
        return $this->belongsTo(country::class);
    }
}
<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use AppModelsCity;

class Country extends Model
{
    use HasFactory;

    public function city()
    {
        return $this->hasMany(city::class);
    }
}
?php

namespace AppModels;

// use IlluminateContractsAuthMustVerifyEmail;
use AppModelsCity;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use LaravelSanctumHasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];

    public function city(){
        return $this->belongsTo(city::class);
    }
}

2

Answers


  1. You’re not handling null chaining correctly. You’ve got this:

    {{ $user->city && $user->city->country ? $user->city->country->name : 'N/A' }}
    

    Which is OK, but then right above it, you have this:

    {{ $user->city->name }}
    

    with no checks… If any User’s City is null, then null->name will trigger, which is not valid.

    Since you’ve got this tagged as laravel-10, which I believe requires PHP 8, you can use the ?-> operator:

    {{ $user?->city?->name ?? 'N/A' }}
    {{ $user?->city?->country?->name ?? 'N/A' }}
    

    If you can’t use that operator, then you need to chain it:

    {{ $user->city ? $user->city->name : 'N/A' }}
    {{ $user->city && $user->city->country ? $user->city->country->name : 'N/A' }}
    
    Login or Signup to reply.
  2. this is a Laravel model error. In your Country and City Models you need to specify either a fillable or a guarded variable. You can read more here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search