Halo pengrajin,
Hari ini kami akan mengembangkan strategi validasi formulir untuk memvalidasi data input.
Pertama buat proyek Laravel dan jalankan perintah ini
komposer create-project –prefer-dist laravel/laravel blog
Buat koneksi database, buat database di database Mysql, lalu buka file .env dan atur nilainya,
buat koneksi database
dan tambahkan kode ke file .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_blog
DB_USERNAME=root
DB_PASSWORD=
Buat rute khusus Anda,
route/web.php
Route::get('user/create',[UserController::class,'create']);
Route::post('user/store',[UserController::class,'store']);
Setelah membuat proyek laravel baru, Anda sudah memiliki model Pengguna dan UserController di direktori proyek Anda.Jika tidak, tambahkan
Buat model
model/pengguna.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Buat pengontrol
application/Http/controllers/UserController.php
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function create(){
return view('user.create_user');
}
public function store(Request $request){
// dd($request);
$validatedData = $request->validate([
'name' => 'required',
'password' => 'required|min:5',
'email' => 'required|email|unique:users'
], [
'name.required' => 'User Name is required',
'password.required' => 'User Password is required'
]);
$validatedData['password'] = bcrypt($validatedData['password']);
$user = User::create($validatedData);
return back()->with('success', 'User created successfully.');
}
}
Dapatkan kode lengkapnya: Validasi formulir Laravel