Home > Software engineering >  laravel 8 update child table data from parent table
laravel 8 update child table data from parent table

Time:12-29

I'm working on a Laravel 8 project.

I have a payments table, it's the migration:

Schema::create('payments', function (Blueprint $table) {
        $table->id();
        $table->enum('gateway',['idpay','zarinpal']);
        $table->unsignedInteger('res_id')->nullable();
        $table->char('ref_code',128)->nullable();
        $table->enum('status',['paid','unpaid']);
        $table->unsignedBigInteger('order_id');
        $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
        $table->timestamps();
    });

as you can see this table has a foreign key that references on orders table, and it is orders migration:

Schema::create('orders', function (Blueprint $table) {
            $table->id();
            $table->unsignedInteger('amount');
            $table->char('ref_code',128)->nullable();
            $table->enum('status',['unpaid','paid',]);
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });

I created a one to one relationship in Order model:

class Order extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function payment()
    {
        return $this->hasOne(Payment::class);
    }
}

The problem is that when I want to use order() method on Payment class it does not work. for example:

Payment::find(10)->order()->update(['status' =>'paid']);

I get this error:

BadMethodCallException Call to undefined method App\Models\Payment::order()

UPDATE: Here is Payment model:

class Payment extends Model
{
    use HasFactory;

    protected $guarded = [];
    
}

Thank you for helping me.

CodePudding user response:

You should use like this a method in the payment model.

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

Because you still don't have any relationship in the payment model to order.

You can check here for detailed information.

https://laravel.com/docs/8.x/eloquent-relationships#one-to-one-defining-the-inverse-of-the-relationship

CodePudding user response:

You have to describe the order relation ship in the Payment model

class Payment extends Model
{
    use HasFactory;

    protected $guarded = [];

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

and after that you can access the payment's order like this:

Payment::find(10)->order->update(['status' =>'paid']);
  • Related