I am trying to generate unique usernames for users upon registration using laravel. I want to include both the first name and the last name. If I use only the first or last name it works, but if I try both, it enters a blank value to the database. Please Help.
Here is my code:
Auth Controller
`
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'firstname'=>'required|max:191',
'lastname'=>'required|max:191',
'phone'=>'required',
'email'=>'required|email|max:191|unique:users,email',
'password'=>'required|min:6',
]);
if($validator->fails())
{
return response()->json([
'validation_errors'=>$validator->messages(),
]);
}
else
{
$userObject = New User;
$userName = $userObject->generateUserName($request['firstname'.'lastname']);
$user = User::create([
'firstname'=>$request->firstname,
'lastname'=>$request->lastname,
'phone'=>$request->phone,
'email'=>$request->email,
'password'=>Hash::make($request->password),
'username'=>$userName,
]);
$token = $user->createToken($user->phone.'_Token')->plainTextToken;
return response()->json([
'status'=>200,
'username'=>$user->firstname,
'token'=>$token,
'message'=>'Registered Successfully',
]);
}
}
`
The User Model
`
public function generateUserName($firstname){
$username = Str::lower(Str::slug($firstname));
if(User::where('username', '=', $username)->exists()){
$uniqueUserName = $username.'-'.Str::lower(Str::random(5));
$username = $this->generateUserName($uniqueUserName);
}
return $username;
}
`
your issue generate from $request['firstname'.'lastname'], you are actually Concating keys of a request array though you want to Concat the value of 2 separate keys which means to use it like this $request['firstname'] and $request['lastname']. please change the below line
$userName = $userObject->generateUserName($request['firstname'.'lastname']);
with this
$userName = $userObject->generateUserName($request['firstname'].$request['lastname']);
Related
I developed a laravel API for flutter app. Here's my AuthController and the following are the function. What I want to do is that once I submit the request on postman, it will display the current info of the logged-in user. Currently, I manage to retrieved the info but it instead display the data of the first user in the table instead of the corresponding user that I logged in(in postman). How do I fix this ? Please help
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function login(Request $request)
{
$fields = $request->validate([
'email' => 'required|string',
'password' => 'required|string'
]);
//Check email
$user = User::where('email', $fields['email'])->first();
//Check password
if (!$user || !Hash::check($fields['password'], $user->password)) {
$result = [];
$result['status'] = false;
$result['message'] = "Bad creds";
return response()->json($result);
} else {
$result = [];
$result['status'] = true;
$result['message'] = "Login successfully";
$data = User::first(['staff_id', 'name']);
$result['data'] = $data;
return response()->json($result);
}
}
}
In your else block the
$data = User::first(['staff_id','name']);
means that it will fetch the first user in your database. Instead of querying again you can use the already declared $user since it is the data that you are looking for.
$data = $user;
How about :
$data = [
'staff_id' => $user->staff_id,
'name' => $user->name,
];
I have one form in frontend where I have there is some city details , rooms details and user registration in one form like I have city name , room name , address etc email addresss and password in same form and I have done 2 logics in one controller for creating cities and registering user
It is saving the both data in correct table in the database
but I want that first user should register and if user is vcerified only the room details should be saved in database
I am in confusion wheather to apply if again or what
public function checkLogin(Request $request)
{
$user = User::create([
'name'=>$request->name,
'email'=>$request->email,
'password'=>$request->password,
'role_id' => config('quickadmin.default_role_id'),
]);
if ($user) {
if (Auth::check()) {
$city = TotalCity::create([
'name'=>$request->name,
'created_by'=>$request->created_by_id,
]);
}
return redirect()->to('/admin/home');
}
}
Let me show you how I'd probably write this logic:
public function checkLogin(Request $request)
{
$user = User::firstOrCreate([
'email'=> $request->email,
],
[
'name'=> $request->name,
'password'=> bcrypt($request->password),
'role_id' => config('quickadmin.default_role_id'),
]);
if (Auth::check()) {
// it's not clear if you utilize `email_verified_at`, if so
// if (Auth::check() && Auth::user()->email_verified_at) {
$city = TotalCity::create([
'name'=>$request->name,
'created_by'=> Auth::user()->id, // or $user->id depending on your preference
]);
}
return redirect('/admin/home');
}
The firstOrCreate() checks if an entry with that email exists, it gets it, otherwise creates it.
Furthermore, if I want to check for Authentication, I'd use 'auth' middleware in my route.
Route::get('example', 'ExampleController#checkLogin')->middleware('auth');
That removes the need of entire check:
if (Auth::check()) { ... }
I am trying to disable the password verification system from my laravel website. I want to login my users using only their first name and last name. Form wise and register wise and database wise, password field has been removed completely. But in login controller, i am having some issues, it does not seem to work. Here is my code:
public function login(Request $request)
{
$first_name = $request->first_name;
$last_name = $request->last_name;
$user = User::where(['first_name' => $first_name, 'last_name' => $last_name])->first();
if (!$user) {
return redirect()->back()->withInput($request->only('first_name', 'last_name'))->withErrors([
'first_name' => 'We could not find you in our database, if you think this is a mistake kindly contact the site administrators',
]);
}
Auth::login($user);
return redirecte('/');
}
in the above code, i am getting the error message
We could not find you in our database, if you think this is a mistake kindly contact the site administrators
regardless of what info (true of false) i insert in my form.
Yes thank you #laravel levaral for answering, but i found out the problem.
I am going to quote a user from laracasts
If you're going to group multiple where clauses into a single where(), each needs to be it's own array, within an array. You're sending a single array. You're also using =>, which isn't correct. The parameters for each where statement are separated by commas.
so for whoever wants to see the new working code:
public function login(Request $request)
{
$first_name = $request->first_name;
$last_name = $request->last_name;
$user = User::where('first_name', $first_name)
->where('last_name', $last_name)
->first();
if (!$user) {
return redirect()->back()->withInput($request->only('first_name', 'last_name'))->withErrors([
'first_name' => 'We could not find you in our database, if you think this is a mistake kindly contact the site administrators',
]);
}
Auth::login($user);
return redirect('/');
}
First of all, you have to check either the first_nameand last_name matches the database.
$user = User::where(['first_name' => $first_name, 'last_name' => $last_name])->first()
You have a problem in above lines.
public function login(Request $request)
{
$first_name = $request->first_name;
$last_name = $request->last_name;
$user = User::where(['first_name' => $first_name, 'last_name' => $last_name])->first();
if (!$user) {
return redirect()->back()->withInput($request->only('first_name', 'last_name'))->withErrors([
'first_name' => 'We could not find you in our database, if you think this is a mistake kindly contact the site administrators',
]);
}
Auth::loginUsingId($user->id);
return redirecte('/');
}
i want to add password update option for logged user therefore i used following code
controller auth\authController.php
public function updatePassword()
{
$user = Auth::user();
$rules = array(
'old_password' => 'required',
'password' => 'required|alphaNum|between:6,16|confirmed'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::route('change-password', $user->id)->withErrors($validator);
} else {
if (!Hash::check(Input::get('old_password'), $user->password)) {
return Redirect::route('change-password', $user->id)->withErrors('Your old password does not match');
} else {
$user->password = Input::get('password');
$user->save();
return Redirect::route('change-password', $user->id)->with("message", "Password have been changed");
}
}
}
Routes
Route::post('change-password', 'Auth\AuthController#updatePassword');
Route::get('change-password', 'Auth\AuthController#updatePassword');
im getting following error
FatalErrorException in AuthController.php line 123:
Class 'App\Http\Controllers\Auth\Auth' not found
for this line "$user = Auth::user();"
Your question has hidden answer..I have similar problem like #faz..I have done the trick with his question's code actually
The correct way to achieve this -
protected function postChangePassword(ChangePasswordFormRequest $request){
$user = Auth::user();
$current_password = Input::get('current_password');
$password = bcrypt(Input::get('password'));
$user_count = DB::table('users')->where('id','=',$this->user_id)->count();
if (Hash::check($current_password, $user->password) && $user_count == 1) {
$user->password = $password;
try {
$user->save();
$flag = TRUE;
}
catch(\Exception $e){
$flag = FALSE;
}
if($flag){
return redirect('/u/0/change/password')->with('success',"Password changed successfully.");
}
else{
return redirect('/u/0/change/password')->with("danger","Unable to process request this time. Try again later");
}
}
else{
return redirect('/u/0/change/password')->with("warning","Your current password do not match our record");
}
}
Please note for Hash and Auth, we need to include class at the top and user_id I have get through constructor $this->user_id = Auth::user()->id;. I think I have helped people.
You didn't import Auth class.
add this at the top of the file. after the namespace.
use Illuminate\Support\Facades\Auth;
Its namespace issue, Try :
//if this method is not protected by a middleware for only authenticated users
//verify that user is currently logged in:
if(!$user = \Auth::user()) abort(503); //or return redirect()->route('login')
$rules = array(
'old_password' => 'required',
'password' => 'required|alphaNum|between:6,16|confirmed'
);
Or Add the namespace at the top of your AuthController
use Auth;
class AuthController{
....
}
As i can understand your issue you just use auth namespace of laravel, just write this line at top of your controller file
use Auth;
will solve your problem.
I'm getting an error on the following on:
$user->email = Input::get('email');
I'm really unsure what is wrong with the code, it seems perfectly fine. I looked up t variable errors, simply involve missing a bracket or semi colon. But as far as I'm aware it seems fine.
If anyone could help me out, that would be great.
If there is any other code, could you list it as a comment and i'll happily add it.
Thanks!
public function doRegister()
{
$rules = array(
'name' => 'required|min:3', // name
'email' => 'required|email', // make sure the email is an actual email
'password' => 'required|alphaNum|min:3' // password can only be alphanumeric and has to be greater than 3 characters
);
// run the validation rules on the inputs from the form
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()){
// validation not successful, send back to form
Redirect::back()->withErrors;
} else {
$user = Input::all();
User::addNewUser();
if (Auth::attempt($user)) {
return Redirect::to('member');
}
}
}
User model
public static function addNewUser()
{
$user = new User;
$user->name = Input::get('name');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
}
It's because of $user->save; it's a method not a property and it should be called like
$user->save();
Instead of
$user->save;
Update : Also, it's U not u
$user = new user;
should be
$user = new User; // capital U
Also, after if ($validator->fails())
Redirect::back()->withErrors;
should be
return Redirect::back()->withErrors($validator);
Update : So, after fixing 3 errors (so far), your full code should be
public function doRegister()
{
$rules = array(
'name' => 'required|min:3',
'email' => 'required|email',
'password' => 'required|alphaNum|min:3'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()){
return Redirect::back()->withErrors($validator);
}
else {
$user = new User;
$user->name =Input::get('name');
$user->email= Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
if (Auth::attempt($user)) {
return Redirect::to('member');
}
}
}