#Validating forms

150 messages · Page 1 of 1 (latest)

dreamy canopy
#

idk whats happening while validating forms it just does not work

#

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

nocturne wolf
#

What does your form look like?

dreamy canopy
#

like code or ui ?

nocturne wolf
#

The code

dreamy canopy
#

oki

dreamy canopy
nocturne wolf
#

Can you try dd($request) at the top of your store function to see if it even reaches the handler

dreamy canopy
#

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';
grave basin
#

how are you saving? like this?

 $product = Product::create($request->validated());
dreamy canopy
#

using events

grave basin
#
$request->validated()
#

that part matters.. it will pass the validated array...

nocturne wolf
#

no just dd the request on your current route

#

see if it even reaches

dreamy canopy
#

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);
stark copper
dreamy canopy
#

oki

dreamy canopy
grave basin
#

rules

dreamy canopy
#

k

stark copper
# dreamy canopy If you dont find can you say little briefly like in which function to move it ru...

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.

dreamy canopy
#

k

#

let me try

#

returns error
Class "App\Http\Controllers\StoreUserRequest" does not exist

stark copper
#

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.

stark copper
dreamy canopy
#

oh yeah in controller right ?

#

now

403
THIS ACTION IS UNAUTHORIZED.
stark copper
#

Did you modified the authorize method in request file as provided in my example?

#

You have to change it to return true;

dreamy canopy
#

yep

stark copper
#

Interesting, can you send a snippet?

#

of both the request and controller?

dreamy canopy
#

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

stark copper
#

That would be caused by the unique rule you have there.

dreamy canopy
#

there is no user with that mail

stark copper
#

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.

dreamy canopy
#

oki

grave basin
#

the controller also won't work as posted..

dreamy canopy
#

another err occurred while getting all users

Class "App\Http\Controllers\DB" not found

but controller contains

use App\Http\Controllers\DB;
grave basin
#

@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?

dreamy canopy
#

is it Illuminate/Support/Facades/DB ?

stark copper
dreamy canopy
#

ignore slash

stark copper
#

There is not DB class in Controllers

#

What program are you using?

dreamy canopy
grave basin
#

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();

grave basin
dreamy canopy
#

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

dreamy canopy
#

So I was just using DB::select()

grave basin
#

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?

dreamy canopy
#

model is imported

#

ig

#

use App\Models\User; right?

#

yes

grave basin
#

correct then if you dd($users) you should have them..

dreamy canopy
#

my index function

public function index()
    {
        $data = Users::all();
        return view('crud.users', compact('data'));
    }
grave basin
#

hmm and still not found?

dreamy canopy
#

i dont get u

dreamy canopy
grave basin
#

I mean after you refresh and go again you still get the error Class "App\Http\Controllers\Users" not found

dreamy canopy
#

ohk

stark copper
#

Sorry I was away, does it wark? 😄

dreamy canopy
#

let me check

grave basin
#

i'm lost now which problem you still have 🙂

dreamy canopy
stark copper
#

Basically in your form you need to have password_confirmation field

dreamy canopy
dreamy canopy
dreamy canopy
dreamy canopy
grave basin
dreamy canopy
#

nah

stark copper
dreamy canopy
#

oki

stark copper
#

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.

dreamy canopy
#

I mostly work with pterodactyl(run on laravel) so few time I need to fixes few issues by my self so I'm learning

dreamy canopy
stark copper
#

And what is the "last" issue again?

dreamy canopy
stark copper
dreamy canopy
#

ohk

#

Just a question

#

I am fimilar with react so should I use react or blade ?

stark copper
dreamy canopy
#

Finally done

#

Thnx bro

grave basin
#

hang on are you saying it worked with ::get() and not all() ?

dreamy canopy
grave basin
#

I'm using ::all() all over the place in many many projects and files with no issues..

dreamy canopy
#

the issue was Users it should be User

grave basin
#

also a tip - if you want to use react you're best when you start a new project installing the breeze/react scaffold

dreamy canopy
#

oki

grave basin
#

ahhhh - really sorry that was a Typo from me 🤦‍♂️

dreamy canopy
#
Laracasts

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...

dreamy canopy
stark copper
#

Instead of elloquent collection?

dreamy canopy
#
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 ?

grave basin
#

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..

dreamy canopy
#

Thnx guys bye ❤️

grave basin
#

@dreamy canopy good luck - don't forget to mark as solved 🙂

dreamy canopy
#

thnx

#

done

stark copper
grave basin
# stark copper 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()

dreamy canopy
#

@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

stark copper
dreamy canopy
#

How do I tell or define it