-2

我有同样的桌子:

id | u_id | f_id

我插入了一些数据,例如:

id   = 1;
u_id = 5;
f_id = 8;

我的问题是,如果他尝试插入相同的数据,我该如何拒绝用户插入?

4

1 回答 1

0

Whenever a new model is saved for the first time, the creating and created events will fire. If a model already existed in the database and the save method is called, the updating / updated events will fire. However, in both cases, the saving / saved events will fire.

For example, let's define an Eloquent event listener in a service provider. Within our event listener, we will call the isValid method on the given model, and return false if the model is not valid. Returning false from an Eloquent event listener will cancel the save / update operation.

<?php

namespace App\Providers;

use App\YourModel;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        YourModel::saving(function ($yourModel) 
        {
            if ( ! $yourModel->isValid() ) 
                return false;

        });
    }
}

In your model add isValid() function, inside this function you'll add your condition :

public function isValid()
{
    if( $this->u_id = 5 && $this->f_id == 8)
        return false;
    else
        return true;
}

NOTE : I guess that the id increment automatically.

Hope this helps.

Source

于 2015-10-10T21:28:17.157 回答