Laravel验证:输入的列必须与登录用户的电子邮件相同

时间:2018-06-26 04:43:33

标签: php laravel validation

我想确保优惠券代码只能由我在优惠券表(Coupons table)中称为受益人的某些用户使用。因此,我使用了laravel验证方法,受益人必须与登录的用户相同,或者可以称为auth()->user()->email,但是我不确定如何在CouponsController.php中编写它。

我checkout.blade.php中的优惠券部分:

<form action="{{ route('coupon.store') }}" method="POST">

    <input type="text" name="coupon_code" id="coupon_code">
    <button type="submit" class="button button-plain">Apply</button>
</form>

CouponsController.php:

public function store(Request $request)
{
    $coupon = Coupon::where('code', $request->coupon_code)->first();

    if (!$coupon) {
        return redirect()->route('checkout.index')->withErrors('Invalid coupon code. Please try again.');
    }

    session()->put('coupon', [
        'name' => $coupon->code,
        'discount' => $coupon->discount(Cart::subtotal()),
        'discountrate' => $coupon->showdiscount(),
        'beneficiary' => $coupon->beneficiary,
    ]);

    $this->validate($request, [ 'beneficiary' => 'same:users,email']);

    return redirect()->route('checkout.index')->with('success_message', 'Coupon has been applied!');
}

1 个答案:

答案 0 :(得分:0)

您可以尝试

public function store(Request $request)
{
    $userEmail = Auth::user()->email; //logged in user email
    $coupon = Coupon::where('code', $request->coupon_code)->where('beneficiary',$userEmail)->first();

    if (!$coupon) {
        return redirect()->route('checkout.index')->withErrors('Invalid coupon code. Please try again.');
    }

    session()->put('coupon', [
        'name' => $coupon->code,
        'discount' => $coupon->discount(Cart::subtotal()),
        'discountrate' => $coupon->showdiscount(),
        'beneficiary' => $coupon->beneficiary,
    ]);

    return redirect()->route('checkout.index')->with('success_message', 'Coupon has been applied!');
}