I am wanting to create a log that informs the registration of a new user, the problem is in the line, i'm wanting to create a log that informs the registration of a new user, the problem is in the line $log_message = Log::channel('logRegisterUser')->info("{$name_user} registered using the IP {$ip_user} in {$data}."); which when placed in a dd() is revealed as null. With this creating error at line 'description_log' => $log_message,.
logging.php
'logRegisterUser' => [
'driver' => 'single',
'path' => storage_path('logs/logRegisterUser.log'),
'level' => 'debug',
],
RegisteredUserController.php
public function __construct()
{
$this->logModel = new LoggingModel();
}
public function create()
{
return view('auth.register');
}
public function store(Request $request)
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
$date = Carbon::now()->format('d/m/Y H:i:s');
$name_user = $user->name;
$ip_user = request()->ip();
$log_message = Log::channel('logRegisterUser')->info("{$name_user} registered using the IP {$ip_user} in {$data}.");
$this->logModel->create([
'description_log' => $log_message,
'relation' => '',
]);
Auth::login($user);
return redirect(RouteServiceProvider::HOME);
}
Log->info() does not return a value. Instead write message in your variable first and then pass it to your Logger :
$log_message = "{$name_user} registered using the IP {$ip_user} in {$data}.";
Log::channel('logRegisterUser')->info($log_message);
Related
I'm using this code for User Sign Up in Laravel:
class UsersController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
'phone' => 'required|unique:users',
'type' => 'boolean',
'verified' => 'boolean'
]);
$user = User::create([
'name' => $validatedData['name'],
'email' => $validatedData['email'],
'phone' => $validatedData['phone'],
'type' => $validatedData['type'],
'verified' => $validatedData['verified'],
'password' => Hash::make($validatedData['password']),
]);
$token = $user->createToken('auth_token')->accessToken;
return response()->json([
'user' => $user,
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
As you can see , some of my field are unique , so I want to display a message in my front side that displays the error from the back side.
Exemple : When a user enters a used phone number , I want to return an error saying : this phone number has been used .
How can I achieve this ? Thank you.
You can get a User record from the database by phone. If the record exists, then do your logic
class UsersController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
'phone' => 'required|unique:users',
'type' => 'boolean',
'verified' => 'boolean'
]);
// get a user record by phone
$record = User::where('phone', $validatedData['phone'])->find();
if (!empty($record)) {
return response()->json([
'error' => 'this phone number has been used'
])
}
//.....
}
ok, I'm trying to login the users after success registration into their panels. the database line built successfully. but alternately user login become successful but once not.
Here is the Request Controller Code:
$request->merge(['phone'=> '09123456789']);
$request->merge(['name' => 'User']);
$request->merge(['password' => 'pass123456789']);
$request->merge(['email' => 'user#email.com']);
$credentials = $request->validate([
'name' => 'required',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/',
'password' => 'required',
'email' => 'required',
]);
User::create([
'name' => $request->name,
'email' => $request->email,
'phone' => $credentials['phone'],
'password' => Hash::make($credentials['password'])
]);
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
return redirect()->route('panel');
}
The Model:
protected $fillable = [
'name',
'phone',
'email',
'password',
];
let me know if I didn't describe perfectly
First, I would stop using validation in the controller and use form request validation instead. It's been the standard since Laravel 5.
Try this simplified code using Auth::login() instead:
public function createUser(Request $request)
{
$request->validate([
'name' => 'required|string|max:64',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/',
'password' => 'required|string|max:64',
'email' => 'required|email|max:64',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'password' => Hash::make($request->password),
]);
Auth::login($user);
return redirect()->route('panel');
}
I'm trying to run this update function in my laravel controller. Here my domain name is an unique attribute.
The problem
But now every time when I'm trying to update any field rather than domain name field, it showing me an error saying domain name is already existing. So how can I update only the fields which have been changed? what changes do I need to be made in the following function.
public function update(Request $request,Website $app, $id)
{
$this->validate($request, [
'subDomainName' => ['required'],
'subDomainSuffix' =>['required'],
'packageType'=>['required'],
'themeid'=>['required'],
'lang'=>['required'],
'user'=>['required'],
'domain' => ['required', 'string','min:2', 'max:255','unique:apps'],
],$request->all());
$fullDomain = $request->domain;
$app->domain=$fullDomain;
Website::find($id)->update($request->all());
return redirect()->route('customers.index')
->with('success','Website updated successfully');
}
You can specify a model to be ignored on the unique attribute:
public function update(Request $request, Website $websiteModel, int $id)
{
$website = $websiteModel->find($id);
$this->validate($request, [
'subDomainName' => ['required'],
'subDomainSuffix' => ['required'],
'packageType' => ['required'],
'themeid' => ['required'],
'lang' => ['required'],
'user' => ['required'],
'domain' => [
'required',
'string',
'min:2',
'max:255',
Rule::unique('apps')->ignore($website)
],
], $request->all());
$website->update($request->all());
return redirect()
->route('customers.index')
->with('success','Website updated successfully');
}
Don't forget to import Rule: use Illuminate\Validation\Rule;
The function below is to update user information, I need to validate if email is not duplicated, also to ignore password if its field left empty, I don't why this function not working!
public function update(Request $request, $id)
{
$this->validate($request->all(), [
'fname' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$input = $request->all()->except(['country_id', 'region_id']);
if(!empty($input['password'])){
$input['password'] = Hash::make($input['password']);
}else{
$input = array_except($input,array('password'));
}
$user = User::find($id);
$user->update($input);
DB::table('model_has_roles')->where('model_id',$id)->delete();
$user->assignRole($request->input('roles'));
return response()->json(array('data' => trans('message.success')));
}
Firstly, you need to correct your validation.
You need to change it to
$request->validate([
'fname' => 'required',
'email' => [
'required',
'email',
Rule::unique('users')->ignore($id),
],
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$request->all() returns an array, you need to change it to
$input = $request->except(['country_id', 'region_id']);
Also I would change the condition to use Laravel's build-in method:
if($request->filled('password'))
Pass the $request object not $request->all(), that returns an array of the input.
$this->validate($request, [
'fname' => 'required',
'email' => [
'required',
Rule::unique('users')->ignore($id),
],
'password' => 'nullable,confirmed',
'roles' => 'required'
]);
I changed the password rule to check if it exists and if it does, it confirms it matches.
Again, I removed the chained all() method
$input = $request->except(['country_id', 'region_id']);
if(!empty($input['password'])){
$input['password'] = Hash::make($input['password']);
}else{
$input = array_except($input,array('password'));
}
Remember to use
use Illuminate\Validation\Rule;
I'm trying to update a user, as an admin.
I'm changing the username, but it says email must be unique.
How do I fix this.
public function update($id, PutUser $request)
{
if (auth()->id() == $id) {
return redirect()->back()->withFlashDanger('Permission Denied, You can not edit own profile here.');
}
$user = User::find($id);
$user->update((array_merge($request->validated(), ['county' => request('county')])));
//Update model_has_roles model with assignees_roles
return redirect()->route('users.index')->withFlashSuccess(trans("alerts.users.updated"));
}
This is the request class
public function authorize()
{
return true;
}
public function rules()
{
$user_id = $this->input('id');
return [
'name' => 'required|string',
'username' => 'required',
'email' => 'required|email|unique:users,email'.$user_id,
'gender' => 'required',
'phone' => 'sometimes|numeric',
'address' => 'sometimes|string',
'country_id' => 'required',
];
}
}
I keep getting a failed email validation. 'Email has already been taken'. Any idea
You are missing a comma after the email label in your validation:
return [
'name' => 'required|string',
'username' => 'required',
'email' => 'required|email|unique:users,email,'.$user_id,
'gender' => 'required',
'phone' => 'sometimes|numeric',
'address' => 'sometimes|string',
'country_id' => 'required',
];
Since Laravel 5.3 (I believe), you can also use rule builders for more descriptive validation rules. Those are better to read and interpret for humans so it would result in a lower error rate:
use Illuminate\Validation\Rule;
return [
'email' => [
'required',
Rule::unique('users', 'email')->except($user_id),
]
];
https://medium.com/#tomgrohl/why-you-should-be-using-rule-objects-in-laravel-5-5-c2505e729b40