当我发送外键时,Laravel Eloquent无法插入行?

This is the method in the controller:

public function buyConfirm($ad_id)
{
    $ad = Ad::find($ad_id);

    $sale = new Sale;
    $sale->ad_id = $ad->id;
    $sale->seller_id = $ad->user->id;
    $sale->buyer_id = \Auth::user()->id;
    $sale->save();

    $x = new Notification;
    $x->ad_id = $ad->id;
    $x->user_id = $ad->user->id;
    $x->type = 'bought';
    $x->view = 0;
    $x->save();

    $ad->delete();

    return \Redirect::route('buyContact',$sale->id)->with('message', 'Done');
}

Laravel insert the first row without problems, but the second register not, in the new Notification dont insert if $ad->id but if a send a harcode value like '4' the insert is successfully, what happend whit this?

The Notification migration:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateNotificationsTable extends Migration
{
    public function up()
    {
        Schema::create('notifications', function (Blueprint $table) {
            $table->increments('id');
            $table->string('type');
            $table->integer('user_id')->unsigned();
            $table->integer('ad_id')->unsigned();
            $table->boolean('view');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('ad_id')->references('id')->on('ads')->onDelete('cascade');
        });
    }

    public function down()
    {
        Schema::drop('notifications');
    }
}

This is the model:

<?php namespace Telovendogdl;

use Illuminate\Database\Eloquent\Model;

class Notification extends Model
{
    protected $table = 'notifications';
    protected $fillable = ['type','ad_id','user_id','view'];

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function ad()
    {
        return $this->belongsTo('App\Ad');
    }
}

I believe your onDelete('cascade') is messing you up.

Right after creating the Notification, you call $ad->delete(). But your migration contains:

$table->foreign('ad_id')->references('id')->on('ads')->onDelete('cascade');

This means that when an ad is deleted, the notification is also deleted.