簡體   English   中英

如何在 laravel-livewire 中設置帶有驗證錯誤的 flash 消息

[英]How in laravel-livewire set flash message with validation erros

在登錄表單中使用 laravel 7 /livewire 1.3 應用程序時,我在無效表單上遇到了錯誤代碼:

public function submit()
{
    $loginRules= User::getUserValidationRulesArray();
    $this->validate($loginRules);

並在任何字段附近顯示錯誤消息

我想在登錄時無法添加 flash 消息並閱讀https://laravel.com/docs/7.x/validation

我試着做:

$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);

if ($validator->fails()) {
    session()->flash('danger_message', 'Check your credentials !');
    return redirect()->to('/login');
}

我收到了 Flash 消息,但任何字段的驗證錯誤都丟失了。

如果我嘗試制作:

$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);

if ($validator->fails()) {
    session()->flash('danger_message', 'Check your credentials !');
    return redirect('/login')
        ->withErrors($validator)
        ->withInput();
}

我得到了錯誤:

Method Livewire\Redirector::withErrors does not exist.

在路由/web.php 我有:

Route::livewire('/login', 'login')->name('login');

修改:在組件 app/Http/Livewire/Login.php 中:

<?php

namespace App\Http\Livewire;

use App\User;
use Illuminate\Support\Facades\Validator;
use Livewire\Component;
use Auth;
use DB;
use App\Config;
use Cartalyst\Sentinel\Laravel\Facades\Sentinel;


class Login extends Component
{
    public $form= [
        'email'=>'admin@mail.com',
        'password'=> '111111',
    ];

    private $view_name= 'livewire.auth.login';


    public function submit()
    {

        $request = request();
        $loginRules= User::getUserValidationRulesArray('login');
        $validator = Validator::make($request->all(), $loginRules);

        if ($validator->fails()) {
            session()->flash('danger_message', 'Check your credentials !');
            return;
//            return redirect()->to('/login');
        }



        $user = Sentinel::findByCredentials(['email'    => $this->form['email']]);
        if (empty($user)) {
            session()->flash('danger_message', 'User "' . $this->form['email'] . '" not found !');
            ...

和模板 resources/views/livewire/auth/login.blade.php :

<article >

    @include('livewire.common.alert_messages')

       <form class="form-login" wire:submit.prevent="submit">

        <div class="card">
                   @if ($errors->any())
                Check your login credentials
            @endif

                <ul>
                 @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                                          @endforeach
                </ul>

            <div class="card-body card-block">

                <h3 class="card-header">
                    <span class="spinner-border" role="status" wire:loading>
                        <span class="sr-only">Loading...</span>
                    </span>
                    Login
                    </h3>
                <h4 class="card-subtitle">Use your credentials</h4>

                <dl> <!-- email FIELD DEFINITION -->

                    <dt>
                        <label class="col-form-label" for="email">Email:<span class="required"> * </span></label>
                    </dt>
                    <dd>
                            <input
                                wire:model.lazy="form.email"
                                name="email"
                                id="email"
                                class="form-control"
                                placeholder="Your email address"
                                autocomplete=off
                                             >
                          @error('form.email')
                        <div class="validation_error">{{ clearValidationError($message,['form.'=>'']) }}</div> @enderror
                    </dd>
                </dl> <!-- <dt> email FIELD DEFINITION -->


                <dl> <!-- password FIELD DEFINITION -->
                    <dt>
                        <label class="col-form-label" for="password">Password:<span class="required"> * </span></label>
                    </dt>
                    <dd>
                         <input type="password"
                               wire:model.lazy="form.password"
                                   id="password"
                                   name="password"
                                   class="form-control"
                                   placeholder="Your password"
                                   autocomplete=off
                                                >
                          @error('form.password')
                        <div class="validation_error">{{ clearValidationError($message,['form.'=>'']) }}</div> @enderror
                    </dd>
                </dl> <!-- <dl> password FIELD DEFINITION -->

            </div> <!-- <div class="card-body card-block"> -->

            <section class="card-footer row_content_right_aligned">
                <button type="reset" class="btn btn-secondary btn-sm m-2">
                    Reset
                </button>
                <button type="submit" class="btn btn-primary btn-sm m-2 ml-4 mr-4 action_link">
                    Submit
                </button>
            </section>


        </div> <!-- <div class="card"> -->

    </form>
</article>

哪種方式有效?

提前致謝!

Livewire 的美妙之處在於您不一定需要重定向以閃爍消息,您可以通過在組件上設置屬性來顯示消息,並有條件地在您的視圖中呈現它們。 在這種特殊情況下,已經有可用的邏輯,您只需要檢查驗證公開的錯誤對象。

在您看來,您所要做的就是檢查@if ($errors->any()) - 如果這是真的,則顯示您的消息。 這是 Laravel 的一個特性,Livewire 實現了它。 當任何驗證失敗時,都會拋出並攔截異常,並且$errors變量會暴露給您的視圖。 這意味着每當您執行$this->validate()並且驗證失敗時,您都可以訪問$errors

<div>
    @if ($errors->any())
        Check your login credentials
    @endif 

    <form wire:submit.prevent="submit">
        <input type="text" wire:model="email">
        @error('email') <span class="error">{{ $message }}</span> @enderror
        
        <input type="password" wire:model="password">
        @error('password') <span class="error">{{ $message }}</span> @enderror
    
        <button type="submit">Submit</button>
    </form>
</div>

使用$rules屬性聲明規則,使用$this->validate()驗證這些規則,Livewire 將為您完成大部分工作。 您不需要返回任何重定向,或使用session()->flash() 會話狀態不會閃爍,因為您沒有執行新頁面加載。

class Login extends Component
{
    public $form = [
        'email' => 'admin@mail.com',
        'password' => '111111',
    ];

    protected $rules;

    private $view_name = 'livewire.auth.login';

    public function submit()
    {
        $this->rules = User::getUserValidationRulesArray('login');
        $this->validate();

        // No need to do any more checks, $errors will now be updated in your view as the exception is thrown
        // Proceed with submitting the form

在渲染方法之前,您可以檢查 errorBag 是否有項目:


    public function render()
    {
        if(count($this->getErrorBag()->all()) > 0){

             $this->emit('error:example');

        }
        return view('livewire-component-view');
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM