php - 如何防止发布重复值?
问题描述
我有一个代码可以从一个看起来像这样的表单中发布详细信息。包含Ampang, Kuala Lumpur
=的字段area_slug
然后,此表单进入一个控制器,该控制器作为 post 函数将值保存在表中。下面是 post 函数中的代码:
if ( $this->outlet->locations->count() ) {
foreach ( $this->outlet->locations as $index => $location ) {
$area = Level2::find( $locations[ $index ][ 'area_id' ] );
$area_slug = ( $area ? $area->slug : '' );
$shipping_fee_value = (float)$locations[ $index ][ 'shipping_fee_value' ];
// two type of conditional checks
// $shipping_fee_allow_negotiate = !empty( $location[ 'shipping_fee_allow_negotiate' ] );
if ( !empty( $locations[ $index ][ 'shipping_fee_allow_negotiate' ] ) ) {
$shipping_fee_allow_negotiate = 1;
} else {
$shipping_fee_allow_negotiate = 0;
}
/**
* Update each location belongs to Outlet
* Laravel Model Insert
* @see https://laravel.com/docs/8.x/eloquent#updates
*/
$location->area_slug = $area_slug;
$location->shipping_fee_value = $shipping_fee_value;
$location->shipping_fee_allow_negotiate = $shipping_fee_allow_negotiate;
$location->update();
}
} else {
foreach ( $locations as $location ) {
$area = Level2::find( $location[ 'area_id' ] );
$area_slug = ( $area ? $area->slug : '' );
$shipping_fee_value = (float)$location[ 'shipping_fee_value' ];
// two type of conditional checks
// $shipping_fee_allow_negotiate = !empty( $location[ 'shipping_fee_allow_negotiate' ] );
if ( !empty( $location[ 'shipping_fee_allow_negotiate' ] ) ) {
$shipping_fee_allow_negotiate = 1;
} else {
$shipping_fee_allow_negotiate = 0;
}
/**
* Create Location and related it to Outlet with `outlet_id`
* Laravel Model Insert
* @see https://laravel.com/docs/8.x/eloquent#inserts
*/
$location = new Location();
$location->outlet_id = $this->outlet->id;
$location->area_slug = $area_slug;
$location->shipping_fee_value = $shipping_fee_value;
$location->shipping_fee_allow_negotiate = $shipping_fee_allow_negotiate;
$location->save();
}
}
所以我想要实现的是防止area_slug
发布相同的内容,例如。Ampang, Kuala Lumpur
在这两个Location 1
和Location 2
各自的领域。我有获得前一个的想法,area_slug
但我不知道该怎么做。如果有任何不清楚的细节,请发表评论。
解决方案
如果你使用 Laravel 的验证,你可以使用它distinct
来确保所有提交位置的唯一性:
$request->validate([
'*.location' => 'distinct',
]);
推荐阅读
- javascript - 是否还有理由将 htmlElement 引用设为空?
- python - Kivy raise FactoryException('Unknown class <%s>' % name) kivy.factory.FactoryException: Unknown class
- ios - iOS:未呈现 NSMutableAttributedString.AddAttributes。(Xamarin)
- kotlin - 在迭代期间更改 MutableList
- ios - 将应用程序提交到 Apple Store 时,IAP verifyReceipt url 应该是沙箱还是服务器上的购买 url?
- c - 如何在 C 中使用 wininet api 将文件上传到 anonfile?
- react-native - 如何使用本机反应创建这样的自定义列表视图?
- sql - DATEDIFF 函数返回 2 行
- c# - 我的 ASP.NET Web 应用程序在 IIS express 上正常运行,但在我发布时却没有
- html - 显示与可见性