Request Data to Model Function - laravel

I'm trying to find out why when I dd($request->all()) in the store method of my controller everything is correct, however when I send it to the model function register() its no where to be seen.
I'm not quite sure what I'm doing wrong.
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class UsersController extends Controller
{
public function store(Request $request, User $user)
{
$this->authorize('delete', $user);
$this->validate($request, [
'firstName' => 'required|min:3',
'lastName' => 'required|min:3',
'displayName' => 'required|min:3',
'emailAddress' => 'required|email|unique:users,email',
'password' => 'required|min:3',
'role' => 'required|exists:roles,id'
]);
$userRegistered = $user->register(
new User($request->all())
);
if ($userRegistered) {
flash()->success('Success', 'The user has been successfully created!');
} else {
flash()->error('Error', 'The user could not be successfully created!');
}
return redirect()->to(route('users'));
}
}
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Authenticatable
{
use SoftDeletes;
/**
* Fillable fields for a user.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'display_name',
'email',
'password',
'role_id'
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function register(User $user)
{
return $user->create([
'first_name' => $user->firstName,
'last_name' => $user->lastName,
'display_name' => $user->displayName,
'email' => $user->emailAdress,
'password' => $user->password,
'role_id' => $user->role
]);
}
}

You've mixed up the formatting of your variables between your request data and your User model.
According to your validation logic, the request data is coming is as camelCase. Yet, according to your $fillable array, the fields on your User model are snake_case. But, even then, in your register method, you're attempting to access the fields on the User model using camelCase.
You haven't given enough information for a definitive answer, but you need to fix the formatting of your variables. For example, change your request fields names from camelCase to snake_case, and make sure you access your fields on the model using snake_case.

You have to pass a list of attributes to "validate" method.
//...
$this->validate($request->all(), [
'firstName' => 'required|min:3',
'lastName' => 'required|min:3',
'displayName' => 'required|min:3',
'emailAddress' => 'required|email|unique:users,email',
'password' => 'required|min:3',
'role' => 'required|exists:roles,id'
]);
One more thing..check if you are using "web" middleware. (Kernel.php => MiddlewareGroups). Add that middleware to your route.

Related

Make register manual laravel with user picture error in file form

Error when I submit form to insert to database. The problem is why picture does not exist?
Method Illuminate\Http\Request::picture does not exist.
This is my Controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\User;
use File;
class UsersController extends Controller
{
public function registeract(Request $request)
{
$this->validate($request,[
'name' => 'required|alpha',
'email' => 'required|email',
'level' => 'required|alpha',
'picture' => 'required|file|image|mimes:jpeg,jpg,png|max:1048',
'password' => 'required'
]);
// Menyiapkan data gambar yg diupload ke variable $file
$picture = $request->picture('picture');
$file_name = time()."_".$picture->getClientOriginalName();
// Isi dengan nama folder tempat kemana file diupload
$upload_directory = 'p_users';
$picture->move($upload_directory, $file_name);
User::create([
'name' => $request->name,
'email' => $request->email,
'level' => $request->level,
'picture' => $file_name,
'password' => bcrypt($request->password),
'remember_token' => Str::random(60)
]);
return redirect('/ec-admin/users')->with('usrsinsertno', 'Data Inserted Successfully!');
}
}
I don't know therefore can use as Model but I see on youtube that there some people use as model.
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'level', 'picture', 'password'
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Picture method doesn't exist on Laravel's request class.
You need to use $picture = $request->file('picture');
Any methods that appear in your head cannot be used.
There is no method like picture in Laravel, as #amirrezam75 mentioned.
Firstly, you need to check if the file exists. You can then save the file and its name.
Try below code:
if ($request->hasFile('picture')) {
$picture = $request->picture('picture');
$file_name = time()."_".$picture->getClientOriginalName();
}else{
$file_name = null;
}

Auto Login After successful registration in laravel 6 getting an error

I am getting an error while trying to Auto Login After successful registration in laravel 6 getting the following error.
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given, called in
My Registercontroller is
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest');
// $this->middleware(['auth','verified']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'min:3'],
'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);
$user = User::create([
'name' => $data['name'],
'username' => $username,
'email' => $data['email'],
'password' => Hash::make($data['password']),
'email_token' => base64_encode($data['email']),
]);
Auth::loginUsingId($user->id);
}
}
User Model
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Jobs\SendEmailJob;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'email','name','password','username','picture',
'ip_address','email_verified_at','email_token','verified'
];
/**
* 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',
];
function socialProviders(){
return $this->hasMany(socialProvider::class);
}
// This is the code define in the sendEmailVerificationNotification
public function sendEmailVerificationNotification()
{
SendEmailJob::dispatch($this);
}
}
You have overwritten the registration logic, but you have ignored the fact that create method needs to return an instance of App\User - or at least a class that implements Authenticatable.
Take a look at the original logic; you will see that the docblock shows that an instance of App\User is being returned and that the original implementation returns the result of the User::create() call.
To get your custom method working, update it like so:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'username' => slugify($data['name'])."-".mt_rand(10000, 99999);,
'email' => $data['email'],
'password' => Hash::make($data['password']),
'email_token' => base64_encode($data['email']),
]);
}
Laravel will take care of logging the user in by default anyway.

Call to a member function details() on null?

My code is:
$user = User::create([
'email' => $request->email,
'password' => Hash::make($request->password),
]);
$user_details = [
'name' => $request->name,
'address' => $request->address,
'lastname' => $request->lastname,
'secondname' => $request->secondname,
'inn' => $request->inn,
'fincode' => $request->fincode,
];
$user->details()->create($user_details);
Model User is:
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
public function details()
{
return $this->hasOne(UserDetails::class, 'user_id', 'id');
}
}
UserDetails model is:
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserDetails extends Model
{
protected $table = 'enterprise';
protected $fillable = ['name', 'lastname', 'secondname', 'address', 'inn', 'fincode'];
}
I believe that your $user has not been persisted, hence having the error, in your case $user is null, that's why you cannot call details on null object. Make sure that you use all the required fields on your user.
You might be missing the fillable array in the User model if the one that you shared is the full content, then add this:
protected $fillable = [ 'email', 'password'];

Laravel Check Email and Provider Exist

I'm using laravel and I want to make auth register and checking by email and provider. Use email and provider because users can register if users login with social media (ex:facebook) have same email like users login with email. I can only make checking by email.
this is my Register Controller
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'username' => 'required|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'provider' => 'unique:users',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
// $prov = 'Email';
return User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'provider' => 'Email',
]);
}
}

Hashing a fillable password

I have no idea how to hash fillable password input. I'm trying to hash it then gets stored to the database. Here's what I've done so far
use App\User;
use Illuminate\Http\Request;
class RegistrationController extends Controller
{
public function store()
{
$this->validate(request(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed'
]);
$pass = bcrypt(request()->password);
$user = User::create(request(['name', 'email', $pass]));
auth()->login($user);
return redirect()->home();
}
}
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password'
];
protected $hidden = [
'password', 'remember_token',
];
}
It gives me a QueryException:
SQLSTATE[HY000]: General error: 1364 Field 'password' doesn't have a default value (SQL: insert into users (name, email, updated_at, created_at) values (the name i inserted, email inserted, date timestamp, date timestamp)
When using: $user = User::create(request(['name', 'email', $pass]));, you are passing an array to the request method and one of the elements ($pass) is not a key of $request.
I believe it should look more like:
$user = User::create([
'name' => request('name'),
'email' => request('email'),
'password' => $pass
]);
EDIT
Also, remember that Laravel provides a Hash facade to help you with encryption:
You can also use the Hash facade to do the same as bcrypt.
Thanks to lagbox for the correction.
$hashedPassword = Illuminate\Support\Facades\Hash:make(request('password'));

Resources