我正在制作的网络应用程序存在问题。关键是,对于用户来说,如果他打算创建一个出发日期(如果他已经有一个),则显示如下错误消息:"哦,你已经签了出发日期。删除先前创建的出发日期以指定新的出发日期!"
DepartureController.php
public function store(Request $request)
{
$request->validate([
'departure_date' => 'required|date|after:yesterday',
'location' => 'required|max:1|integer|',
]);
$date = Carbon::parse($request->departure_date);
$LocationUsers = new LocationUser();
$LocationUsers->user_id = request()->user()->id;
$LocationUsers->departure_date = $date;
$LocationUsers->location_id = $request->location;
$LocationUsers->save();
session()->flash('success', 'Departure added succesfully!');
return redirect('departure/create');
}
用户模型
public function daysUntilDeparture()
{
if ($this->location()->count() < 1) {
return "No departure date has been given";
}
$location = $this->location[0];
$userLocation = LocationUser::where('user_id', $this->id)
->where('location_id', $location->id)
->first();
$departure_date = $userLocation->departure_date;
return $departure_date->diffInDays(Carbon::now());
}
答案 0 :(得分:0)
您可以创建自己的验证规则(https://laravel.com/docs/5.6/validation#custom-validation-rules)
例如,您的规则可能如下所示:
use Illuminate\Contracts\Validation\Rule;
class CurrentDeparture implements Rule
{
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
return is_null(LocationUser::where('user_id', request()->user()->id)->first());
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'Uh oh, you have already made a departure date. Delete the previously made departure date to assign a new one!';
}
}
您的验证将是:
$request->validate([
'departure_date' => [new CurrentDeparture, 'required', 'date', 'after:yesterday'],
]);