skip to Main Content

when a foreign key value is null I want to return a specific value from the model because when I delete the primary key id row and set a null value on the foreign key shows error. how to can I do it please anybody help me?

Here Is My Country Migration Table:

public function up()
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->id();
            $table->string('name', 60)->nullable();
            $table->string('country_code', 60)->nullable();
            $table->string('capital', 120)->nullable();
            $table->string('region', 120)->nullable();
            $table->string('currency_code', 120)->nullable();
            $table->string('currency_name', 120)->nullable();
            $table->string('currency_symbol', 120)->nullable();
            $table->string('language_code', 120)->nullable();
            $table->string('language_name', 120)->nullable();
            $table->bigInteger('flag')->unsigned()->nullable();
            $table->foreign('flag')->references('id')->on('media_files')->onDelete('cascade')->onUpdate('cascade');
            $table->string('dialling_code', 10)->nullable();
            $table->integer('status')->default(0)->unsigned();
            $table->timestamps();
        });
    }

Here Is My City migration Table:

Schema::create('cities', function (Blueprint $table) {
            $table->id();
            $table->string('name')->nullable();
            $table->string('zipcode')->nullable();
            $table->string('order')->default(null)->nullable();
            $table->foreignId('country_id')->nullable()->constrained("countries")->cascadeOnUpdate()->nullOnDelete();
            $table->timestamps();
        });

City Model:

class City extends Model
{
    use HasFactory;

    public function country(){
        return $this->belongsTo(Country::class,'country_id');
    }
}

Frontend Blade:

<tbody>
                    @foreach($CityList as $City)
                      <tr>
                        <td><input type="checkbox" name="id[]"></td>
                        <td>{{$City->id }}</td>
                        <td>{{$City->name }}</td>
                        <td>{{$City->zipcode }}</td>
                        <td>{{$City->country->name }}</td>
                        <td>{{$City->country->countrycode }}</td>
                        <td>{{$City->order }}</td>
                        <td>{{$City->created_at->diffForHumans()}}</td>
                        <td>
                          <a href="{{ route('dashboard.city.edit',$City->id) }}" class="btn btn-info" data-toggle="tooltip" title="Edit"><i class="fa fa-edit" style="font-size: 17px;"></i></a>
                          <button href="{{ route('dashboard.city.delete',$City->id) }}" type="button" value="{{ $City->id }}" class="btn btn-danger delete" data-toggle="tooltip" title="Delete">
                            <i aria-hidden="true" class="fa fa-trash"></i>
                          </button>
                        </td>
                      </tr>
                    @endforeach
                </tbody>

enter code here

enter image description here

2

Answers


  1. You can do this: <td>{{$City->country ? $City->country->name : 'No country found'}}</td>

    And make sure you are including countries when fetching cities.

    Login or Signup to reply.
  2. I can suggest a few ways to solve this

    First: Make a default value for the relation, like here

    public function country()
    {
        return $this->belongsTo(...)->withDefault(['name' => 'No country']);
    }
    

    Second: Make a mutation in City model to find the name of the country

    protected function countryName(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => $this->country-> name ?? 'Not country',
        );
    }
    

    Notes: This way works only for laravel 9.x +, for older versions
    please read this article

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