Hello Artisan,
Today we will make form validation strategies to make input data validated.
Create a Laravel Project first, run this command
composer create-project –prefer-dist laravel/laravel blog
Make databse Connection , create a database in the Mysql database after that go to the .env file and set the values,
Make Database Connection
and add the code to .env file
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_blog
DB_USERNAME=root
DB_PASSWORD=
Create your custom route,
routes/web.php
Route::get('user/create',[UserController::class,'create']);
Route::post('user/store',[UserController::class,'store']);
After creating a brand new laravel project you have already the User model and UserController in your project directory. If not then add
Create Model
Models/User.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',
];
}
Create Controller
app/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.');
}
}
GET FULL CODE: Laravel Form Validation
Top comments (0)