This is my RegisterController (Laravel ui edited). please help me.
Is i have to add any other page to this question.
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'name_of_firm' => $data['name_of_firm'],
'number' => $data['number'],
'address' => $data['address'],
]);
}
There is 2 case if name_of_firm is nullable or required
Case : 1
if name_of_firm is required
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
'name_of_firm' => ['required']
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'name_of_firm' => $data['name_of_firm'],
'number' => $data['number'],
'address' => $data['address'],
]);
}
Case : 2
if name_of_firm is nullable
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'name_of_firm' => $data['name_of_firm'] ?? null, // make sure database is accept null value
'number' => $data['number'],
'address' => $data['address'],
]);
}
you should use data_get or Arr::get() helpers to solved not exists element:
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'name_of_firm' => data_get($data, 'name_of_firm'),
'number' => data_get($data, 'number'),
'address' => data_get($data, 'address')],
]);
}
Related
I'm getting this error on Laravel Auth register
Call to a member function validate() on null
The error only happens when the validation passes, when it fails it shows returns to the register view with the correct errors.
I tried to dd after the if fails but it doesn't reach it:
protected function validator(array $data){
$req = new Request($data);
//dd($req,$data);
$this->validate($req,
[
'name' => ['required', 'string', 'max:50','min:3'],
'email' => ['required','email', 'unique:users'],
'password' => ['required', 'min:8', 'confirmed'],
'uni' => ['required'],
'city' => ['required'],
],[
'required' => 'هذا الحقل مطلوب',
'email'=>'نمط البريد الالكتروني غير صحيح',
'min'=>'يجب إدخال 8 حروف عالأقل',
'email.unique' => 'هذا البريد الالكتروني مستخدم',
'confirmed'=>'الرجاء التأكد من كلمة المرور',
'max'=>'50 حرف هو أقصى حد يمكن إدخاله',
'name.min'=>'الاسم قصير جدا',
]);
}
protected function create(array $data){
if ($this->validator($data)->fails()) {
return Redirect::back()->withErrors($this->validator($data))
->withInput();
}
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'photo'=>'img/user.jfif',
'university'=>$data['uni'],
'city'=>$data['city'],
]);
}
full code of RegisterController
https://pastebin.com/B8XcNbBR
and RegistersUsers (where the stack trace shows the error)
https://pastebin.com/BBTTStLL
Try this one
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:50','min:3'],
'email' => ['required','email', 'unique:users'],
'password' => ['required', 'min:8', 'confirmed'],
'uni' => ['required'],
'city' => ['required'],
],[
'required' => 'هذا الحقل مطلوب',
'email'=>'نمط البريد الالكتروني غير صحيح',
'min'=>'يجب إدخال 8 حروف عالأقل',
'email.unique' => 'هذا البريد الالكتروني مستخدم',
'confirmed'=>'الرجاء التأكد من كلمة المرور',
'max'=>'50 حرف هو أقصى حد يمكن إدخاله',
'name.min'=>'الاسم قصير جدا',
]);
}
protected function create(array $data){
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'photo'=>'img/user.jfif',
'university'=>$data['uni'],
'city'=>$data['city'],
]);
}
If I change validate by validator->fails return redirect..... I get error because login want an instance of $user and I send a response.
This defaults work well but not for me
public function create(array $input)
{
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => $this->passwordRules(),
'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['required', 'accepted'] : '',
])->validate();
return User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
]);
}
Thats give me a:
Illuminate\Auth\SessionGuard::login(): Argument #1 ($user) must be of type Illuminate\Contracts\Auth\Authenticatable, Illuminate\Http\RedirectResponse given, called in ....endor/laravel/fortify/src/Http/Controllers/RegisteredUserController.php on line 57
public function create(array $input)
{
$validator = Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => $this->passwordRules(),
'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['required', 'accepted'] : '',
]);
if($validator->fails()) {
return Redirect::to(URL::previous() . "#my-anchor")->withInput()->with('error', $validator->messages()->first());
} //Thats I want
return User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
]);
}
I don't did this before but maybe you can find the way to customize it. The CreateNewUser is called in the RegisteredUserController's store method, and the first return an User's instance. So in this you can
if($validation->fails())
return $validation->messages()->first();
and in the store method
public function store(Request $request, CreatesNewUsers $creator): RegisterResponse
{
$user = $creator->create($request->all()));
if($user instanceof User::class) {
event(new Registered($user);
$this->guard->login($user);
return app(RegisterResponse::class);
} else
return Redirect::to(URL::previous()."#my-anchor")->withInput()->with('error', $user);
}
Try this, but I suggest you if works extends this Register controller and just modify this store method
User password changes in Laravel 8 after a period of time post logout, maybe a day or more. When I look into the database, the password hash has changed. I used the default Laravel authentication and had this issue, so I wrote the login code below, but still, I have the issue.
LoginController
public function login(Request $request)
{
$email_username = filter_var($request->username, FILTER_VALIDATE_EMAIL) ?
'email' : 'username';
$request->merge([$email_username => $request->username]);
if (Auth::attempt($request->only($email_username, 'password'))) {
return redirect()->intended($this->redirectTo);
} else {
return view('auth.login')
->with('these credetials do not match our records.');
}
$user = User::where($email_username, $request->username)->get();
if ($user && Hash::check($request->password, $user->password)) {
$request->session()->regenerate();
auth()->login($user);
return redirect()->intended($this->redirectTo);
}
return redirect()->back();
}
User Model
class User extends Authenticatable
{
use HasFactory, Notifiable;
public function partners()
{
return $this->hasMany('App\Models\partner');
}
protected $fillable = [
'username',
'profilepic',
'firstname',
'lastname',
'password',
'email',
'title',
'phone',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
and this is the method that registers user.
public function store(Request $request)
{
$request->validate([
'username' => ['required', 'string', 'max:255', 'unique:users'],
'profilepic' => ['required', 'image', 'mimes:jpeg,png,jpg,gif,svg,ico', 'max:2048'],
'firstname' => ['required', 'string', 'max:255'],
'lastname' => ['required', 'string', 'max:255'],
'password' => ['required', 'string', 'min:8'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'title' => ['required', 'string', 'max:255'],
'phone' => ['required', 'min:10'],
]);
if ($request->profilepic != null) {
$profilepic = $request->firstname . ' ' . $request->lastname . '.' . $request->profilepic->extension();
$request->profilepic->move(public_path('/global_assets/images/users/'), $profilepic);
}
$user = new User([
'username' => $request->get('username'),
'profilepic' => $profilepic,
'firstname' => $request->get('firstname'),
'lastname' => $request->get('lastname'),
'password' => Hash::make($request->get('password')),
'email' => $request->get('email'),
'title' => $request->get('title'),
'phone' => $request->get('phone'),
'isAdmin' => $request->get('isAdmin'),
'isActive' => $request->get('isActive'),
]);
$user->save();
return redirect()->back()->with('success', 'New user has been created.');
}
I hope you can help me, I wanna customize the registercontroller from Laravel, I have this, but after the user is registered send me a JSON of data, how can I do for don't send me the JSON and redirect to the HomeController.
Thanks.
PD. Sorry for my English.
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => ['required', 'string', 'max:255'],
'nombre' => ['required', 'string', 'max:255','unique:users'],
'telefono' => ['required', 'numeric', 'max:99999999', 'min:00000000'],
'direccion' => ['required', 'string', 'max:255'],
'sueldo' => ['numeric','min:0.01','max:0.99'],
//'foto' => ['string', 'max:255'],
'email' => ['string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:4', 'confirmed'],
]);
if ($request->hasFile('foto')) {
$request = request();
$file = $request->file('foto');
$nom_imagen = time().".".$file->getClientOriginalExtension();
$upload_path = 'imagenes/';
$profile_image_url = $upload_path . $nom_imagen;
$success = $file->move($upload_path, $nom_imagen);
} else {
$nom_imagen = '';
}
return User::create([
'name' => $request->input('name'),
'nombre' => $request->input('nombre'),
'telefono' => $request->input('telefono'),
'direccion' => $request->input('direccion'),
'sueldo' => $request->input('sueldo'),
'email' => $request->input('email'),
'foto' => $nom_imagen,
'password' => Hash::make($request['password']),
return redirect()->action('HomeController#index'),
]);
}
Laravel 5.5: Execute a method before registration
HomeController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('index');
}
}
You are returning the return value of User::create() which will be a User object which gets converted to json when returned as a response.
Also since your HomeController is protected by 'auth' middleware you need to login the user before redirecting to '/home'
use Illuminate\Support\Facades\Auth;
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => ['required', 'string', 'max:255'],
'nombre' => ['required', 'string', 'max:255','unique:users'],
'telefono' => ['required', 'numeric', 'max:99999999', 'min:00000000'],
'direccion' => ['required', 'string', 'max:255'],
'sueldo' => ['numeric','min:0.01','max:0.99'],
//'foto' => ['string', 'max:255'],
'email' => ['string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:4', 'confirmed'],
]);
if ($request->hasFile('foto')) {
$request = request();
$file = $request->file('foto');
$nom_imagen = time().".".$file->getClientOriginalExtension();
$upload_path = 'imagenes/';
$profile_image_url = $upload_path . $nom_imagen;
$success = $file->move($upload_path, $nom_imagen);
} else {
$nom_imagen = '';
}
$user = User::create([
'name' => $request->input('name'),
'nombre' => $request->input('nombre'),
'telefono' => $request->input('telefono'),
'direccion' => $request->input('direccion'),
'sueldo' => $request->input('sueldo'),
'email' => $request->input('email'),
'foto' => $nom_imagen,
'password' => Hash::make($request['password']),
]);
Auth::guard()->login($user);
return redirect('/home');
}
Move the redirect after create user , try like this
User::create([
'name' => $request->input('name'),
'nombre' =>$request->input('nombre'),
'telefono' => $request->input('telefono'),
'direccion' => $request->input('direccion'),
'sueldo' => $request->input('sueldo'),
'email' => $request->input('email'),
'foto' => $nom_imagen,
'password' => Hash::make($request['password'])
]);
return redirect()->action('HomeController#index'),
I want to remove validation on the name in laravel 6 on creating a new user. The user is created successfully but when I enter a name with space or capital letters, the login page opens up. But if I remove all spaces from the name everything works fine with the following code.
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data)
{
$username = slugify($data['name']) . "-" . mt_rand(10000, 99999);
return User::create([
'name' => $data['name'],
'username' => $username,
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
blade.php code
https://codeshare.io/5e1kX7
Try
//...
'name' => ['required', 'string', 'regex:/^[a-zA-Z0-9\s]+$/', 'max:255'],
//...
I did it by adding regex in the validation
'name' => ['required', 'string','regex:/^[\pL\s\-]+$/u', 'max:255'],