Laravel避免重复输入模型 [英] Laravel avoid duplicate entry from model

查看:68
本文介绍了Laravel避免重复输入模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建Laravel API.我有一个名为Reservations的模型.我要避免用户为相同的产品和时间段创建两个预订.

I'm building a Laravel API. I have a models called Reservations. I want to avoid that a user creates two reservations for the same product and time period.

我有以下内容:

$reservation =  Reservation::firstOrCreate([
   'listing_id'    =>  $request->listing_id,
   'user_id_from'  =>  $request->user_id_from,
   'start_date'    =>  $request->start_date,
   'end_date'      =>  $request->end_date,
]);

评论后

我也在使用验证

 $validator = Validator::make($request->all(), [
            'listing_id'    =>  'required|exists:listings,id',
            'user_id_from'  =>  'required|exists:users,id',
            'start_date'    =>  'required|date_format:"Y-m-d"|after:today',
            'end_date'      =>  'required|date_format:"Y-m-d"|after:start_date'
        ]);

        if ($validator->fails()) {
            return response()->json(['error' => 'Validation failed'], 403);
        }

验证工作正常.

编辑结束

在我的模型中,我已将开始日期和结束日期转换为dates.

In my model I have casted the start_date and end_date as dates.

class Reservation extends Model
{
    protected $fillable = ['listing_id', 'start_date', 'end_date'];
    protected $dates = [
        'start_date',
        'end_date'
    ];
    ....
    ....

文档说:

firstOrCreate方法将尝试查找数据库记录 使用给定的列/值对

The firstOrCreate method will attempt to locate a database record using the given column / value pairs

但是我仍然可以插入具有相同属性的条目.

However I notice that I'm still able to insert entries with the same attributes.

有任何想法我做错了什么或建议如何解决?

Any idea what I'm doing wrong or suggestions to fix it?

推荐答案

您可以使用Laravel内置的ValidateRequest类实现此目的.此验证最简单的用例是直接在您的store()方法中调用它,如下所示:

You can achieve this using Laravel's built in ValidateRequest class. The most simple use-case for this validation, is to call it directly in your store() method like this:

public function store(){

   $this->validate($request, [
      'listing_id' => 'required|unique,
      'start_date' => 'required|unique,
      //... and so on
   ], $this->messages);

   $reservation =  Reservation::firstOrCreate([
      'listing_id'    =>  $request->listing_id,
      'user_id_from'  =>  $request->user_id_from,
      'start_date'    =>  $request->start_date,
      'end_date'      =>  $request->end_date,
   ]);
}

以此来验证用户$request,方法是说指定的列为required且它们必须为unique才能通过验证. 如果不满足条件,您还可以在控制器中创建消息功能以显示错误消息.

With this, you're validating users $request with by saying that specified columns are required and that they need to be unique, in order for validation to pass. In your controller, you can also create messages function to display error messages, if the condition isn't met.

private $messages = [
      'listing_id.required' =>  'Listing_id is required',
      'title.unique' => 'Listing_id already exists',
      //... and so on 

    ];

您还可以通过创建一个新的自定义验证类来实现此目的:

You can also achieve this by creating a new custom validation class:

php artisan make:request StoreReservation

生成的类将放置在app/Http/Requests目录中.现在,您可以向rules方法添加一些验证规则:

The generated class will be placed in the app/Http/Requests directory. Now, you can add a few validation rules to the rules method:

public function rules()
{
    return [
      'listing_id' => 'required|unique,
      'start_date' => 'required|unique,
      //... and so on
    ];
}

您现在要做的就是在控制器方法上键入请求的提示.传入的表单请求将在调用controller方法之前进行验证,这意味着您无需使用任何验证逻辑来​​使您的控制器变得混乱:

All you need to do now is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic:

public function store(StoreReservation $request)
{
    // The incoming request is valid...

    // Retrieve the validated input data...
    $validated = $request->validated();
}

如果您对此还有其他疑问,请随时提问.来源:Laravel官方文档.

If you have any additional question about this, feel free to ask. Source: Laravel official documentation.

这篇关于Laravel避免重复输入模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆