#Validating forms
150 messages · Page 1 of 1 (latest)
code
public function store(Request $request): RedirectResponse
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
return redirect()->route('users');
}
this is my store function
in this part of I enter data manually in the controller it works
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
but not working when submitting
What does your form look like?
like code or ui ?
The code
oki
Can you try dd($request) at the top of your store function to see if it even reaches the handler
and web.php
<?php
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::get('/users', [UserController::class, 'index'])->name('users');
Route::get('/create-user', [UserController::class, 'create']);
Route::post('/create-user', [UserController::class, 'store'])->name('new-user');
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');
Route::middleware('auth')->group(function () {
Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});
require __DIR__.'/auth.php';
how are you saving? like this?
$product = Product::create($request->validated());
using events
shall I create a new route ?
smthng like this
?
$data = $request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
dd($data);
I'd advice you to run php artisan make:request StoreUserRequest and move your validation logic there. Then replace the Request in your store() with StoreUserRequest $request. Then calling $request->validated() will return you validation passed data.
oki
If you dont find can you say little briefly like in which function to move it rules/authorize ?
rules
k
Use:
php artisan make:request StoreUserRequest
navigate to StoreUserRequest.php in app/Http/Requests
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules;
class StoreUserRequest extends FormRequest
{
public function authorize()
{
return true; // Modify this according to your authentication logic
}
public function rules()
{
return [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
];
}
}```
Then just use it in your Controller
```use App\Http\Requests\StoreUserRequest;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Hash;
use Illuminate\Auth\Events\Registered;
public function store(StoreUserRequest $request): RedirectResponse
{
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
return redirect()->route('users');
}```
Idk what is Rules\Password::defaults() tho.
So it could throw an error.
k
let me try
returns error
Class "App\Http\Controllers\StoreUserRequest" does not exist
Also I'd avoid to calling $request->name etc, best is to call for validated data either by using ->validated() or ->safe(), you can read more about them in Laravel docs. They'd assure you are processing trully validated data only.
Did you imported it in your controller?
use App\Http\Requests\StoreUserRequest;
Did you modified the authorize method in request file as provided in my example?
You have to change it to return true;
yep
oki
req
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'confirmed'],
];
}
}
Controller
public function store(StoreUserRequest $request): RedirectResponse
{
// $data = $request->validate([
// 'name' => ['required', 'string', 'max:255'],
// 'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
// 'password' => ['required', 'confirmed', Rules\Password::defaults()],
// ]);
// dd($data);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
return redirect()->route('users');
}
i just done some thing it fixed but returns
That would be caused by the unique rule you have there.
there is no user with that mail
No, it's a select error.
This is wrong
there should be a name of the table and a column provided if I am right. I always use Rule::unique() tho instead of this string definition.
User::class returns "App\Http\Requests\User" which should be "App\Models\User" but that doesn't matter right now. You have to put your users table there.
Seems 'unique:users' should be sufficient.
oki
the controller also won't work as posted..
another err occurred while getting all users
Class "App\Http\Controllers\DB" not found
but controller contains
use App\Http\Controllers\DB;
@stark copper mentioned you need to use $request->validated() or safe() then will work also in the docs on user you 'may' use the model directly if you want
'email' => 'unique:App\Models\User,email_address'
what is that? Controllers\DB?
is it Illuminate/Support/Facades/DB ?
Oh, you can provide class there? Interesting. Well, I always used the Rule facade for this to avoid writing string like this. 😄
ignore slash
sorry ?
if you're using that but in your routes you have Route::get('/users', [UserController::class, 'index'])->name('users');
I bet you have that Facade in the usersController but you don't need it really
$users = Users::all();
Yeah i also prefer that.. just another option I guess..
still the issue is not fixed of creating user
like validating form
@stark copper please help I'm try to do this since 2days
Ohhhhhhh
Finlly fixed it
the isssue was coming here 'password' => ['required', 'confirmed'],
idh any confirm field
so i removed it it works
Thnx guys
for that I get this error
Class "App\Http\Controllers\Users" not found
So I was just using DB::select()
Exactly - when you type Users normally you're IDE will give you the option to import the model - otherwise just import the model
use App\Models\User;
Imported in the controller?
correct then if you dd($users) you should have them..
my index function
public function index()
{
$data = Users::all();
return view('crud.users', compact('data'));
}
hmm and still not found?
i dont get u
where is the issue ?
I mean after you refresh and go again you still get the error Class "App\Http\Controllers\Users" not found
ohk
Sorry I was away, does it wark? 😄
let me check
i'm lost now which problem you still have 🙂
ye
getting users with $users = Users::all()
You need confirmed, it's for the "second" try for a password so user won't mistype it.
Basically in your form you need to have password_confirmation field
Like to create user from admin side
when user create acc noramlly it is available any ways i am using breeze
Vel bro help me out with this
still same
have you cached anything (please don't if you haven't)
nah
I think it would be best for you to sort of open LaraCast and run through a base courses so you'd understand how it works.
oki
Because I think you are missing a lot of knowledge you are supposed to have trying to achieve this.
Don't get me wrong, it could take you only a few hours of courses, so you'd be able to program this even today. If you'll not rush it.
I mostly work with pterodactyl(run on laravel) so few time I need to fixes few issues by my self so I'm learning
thats ok bro np
anyways can you help with this last thing
I started with Laracasts a long time ago and it helped me understand a lot of things.
And what is the "last" issue again?
this one 👆
You should get users with User::get()
React is a javascript framework, blade is just html templating. I mean, you can use whatever suits you and needs of your project best.
oki
hang on are you saying it worked with ::get() and not all() ?
actually bros
I'm using ::all() all over the place in many many projects and files with no issues..
the issue was Users it should be User
also a tip - if you want to use react you're best when you start a new project installing the breeze/react scaffold
oki
ahhhh - really sorry that was a Typo from me 🤦♂️
shall I go with this
https://laracasts.com/series/30-days-to-learn-laravel-11
Laravel is an incredible and mature PHP framework that has sky-rocketed in popularity since its initial introduction back in 2012. I'm happy to say that I've been a user and advocate for the framework since the beginning. I'd love to show you the ropes if you're willing! Together, we'll review each piece of the framework, and wrap up by building...
aww np
i just saw few laravel+react templates, they use react-dom in which I'm really bad
doesn't all return an array?
Instead of elloquent collection?
Illuminate\Database\Eloquent\Collection {#1022 ▼ // app\Http\Controllers\UserController.php:25
#items: array:3 [▼
0 =>
App\Models
\
User {#1288 ▶}
1 =>
App\Models
\
User {#1289 ▶}
2 =>
App\Models
\
User {#1290 ▶}
]
#escapeWhenCastingToString: false
}
dd() works with any type of route ?
dd stands for dump and die so you can use it in your backend to help with debugging problems - @stark copper I did a quick test on all() vs get() and in both cases there is a collection of models returned..
ig this is what it returns
Thnx guys bye ❤️
correct but the question was about using get() vs all() and it turns out both methods return the same in this case..
@dreamy canopy good luck - don't forget to mark as solved 🙂
So what is the difference then? o.O
I can't really find one - i 'suspect' all() is just a shortcut, meaning if you use model::where(something) then you need to use get() or first() in that case get() still returns a collection and first() returns the model object, I learned something new today though, i think for consistency using get() with no args can be a bit cleaner, unless I miss something...interestingly all() has a dock block but my IDE (vsCode) doesn't pick that up for get()
@grave basin Hello
I just have a confusion
How does the StoreUserRequest know to only captue data of a single route which we haven't defined in StoreUserRequest.php
It doesn’t unless you tell it to. You can reuse on multiple routes.
How do I tell or define it