Nggunakake Validation Fitur ing Laravel: Priksa lan Proses Data Input

Kanggo validasi lan ngolah data input saka formulir nggunakake validation fitur ing Laravel, tindakake langkah iki:

 

Netepake Validation Aturan

Miwiti kanthi nemtokake validation aturan kanggo kolom formulir sampeyan. Laravel nyedhiyakake macem-macem validation aturan sing bisa digunakake kanggo njamin integritas lan validitas data.

public function store(Request $request)  
{  
    $validatedData = $request->validate([  
        'name' => 'required|max:255',  
        'email' => 'required|email|unique:users|max:255',  
        'password' => 'required|min:8',  
    ]);  
  
    // Process the validated data  
    $user = User::create([  
        'name' => $validatedData['name'],  
        'email' => $validatedData['email'],  
        'password' => Hash::make($validatedData['password']),  
    ]);  
  
    // Redirect to a success page or perform other actions  
    return redirect()->route('users.index')->with('success', 'User created successfully.');  
}  

Ing conto ing ndhuwur, kita nemtokake validation aturan kanggo kolom jeneng, email, lan sandhi. Aturan kasebut required njamin yen kolom ora kosong, email aturan kasebut validasi format email, unique:users aturan mriksa yen email kasebut unik ing users  tabel, lan aturan max lan min  nemtokake dawa maksimum lan minimal kanggo kolom sandi.

 

Ngalahake Validation Asil

Laravel 's validation fitur otomatis performs validation adhedhasar aturan ditetepake. Yen validation gagal, Laravel bakal pangalihan pangguna bali menyang formulir karo pesen kesalahan cocok. Sampeyan bisa njupuk pesen kesalahan iki ing tampilan kanggo nampilake menyang pangguna.

<!-- Display validation errors -->  
@if($errors->any())  
    <div class="alert alert-danger">  
        <ul>  
            @foreach($errors->all() as $error)  
                <li>{{ $error }}</li>  
            @endforeach  
        </ul>  
    </div>  
@endif  
  
<!-- Create user form -->  
<form method="POST" action="{{ route('users.store') }}">  
    @csrf  
    <input type="text" name="name" placeholder="Name" value="{{ old('name') }}">  
    <input type="email" name="email" placeholder="Email" value="{{ old('email') }}">  
    <input type="password" name="password" placeholder="Password">  
    <button type="submit">Create User</button>  
</form>  

Ing kode ing ndhuwur, kita mriksa yen ana validation kesalahan lan nampilake ing kothak tandha. Fungsi kasebut old() digunakake kanggo ngisi maneh kolom formulir kanthi nilai sing wis dilebokake sadurunge yen ana validation kesalahan.

 

Kanthi nderek conto iki, sampeyan bisa validasi lan ngolah data input saka formulir nggunakake validation fitur ing Laravel. Iki mesthekake yen data kasebut cocog karo aturan sing wis ditemtokake lan mbantu njaga integritas data ing aplikasi sampeyan.