I tried adding a position to my user and setting it on users_positions table.
I created a new query alongside with the auth user create. When re-routing it to the root URL, it always comes back as
InvalidArgumentException
Route [/] not defined.
Controller
protected function create(array $data)
{
$id = User::create([
'firstname' => $data['firstname'],
'middlename' => $data['middlename'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'username' => $data['username'],
'password' => Hash::make($data['password']),
]);
DB::table('users_positions')->insert([
[
'user_id' => $id->id,
'position_desc' => $data['position'],
'primary' => "1",
]
]);
return redirect()->route('/')
->with('success', 'Successfully added a user account');
}
Route
Auth::routes();
Route::get('/home', 'HomeController#index')->name('name');
Route::get('/', function () {
return view('incident-reports.index');
})->middleware('auth');
The query is successful but the route still not defined.
When I try manually going to the root URL http://127.0.0.1:8000. It will work.
My plan is after adding user and the user_position it will come back at root URL and prompting an alert if it is success or error.
if you want to redirect with the path, send it as parameter to redirect() method
return redirect('/');
the route() method is to redirect to a route by Alias
route
Route::get('/', function () {
return view('incident-reports.index');
})->middleware('auth')->alias('root');
redirect
return redirect()->route('root');
Change this line:
return redirect()->route('/')
->with('success', 'Successfully added a user account');
to this
return redirect()->to('/')
->with('success', 'Successfully added a user account');
route() expects a route name as argument. '/' is a url
Related
I made a manual login system in a Laravel 9 API that it's works correctly, but when I try to use Auth::user() in another controller, I get it as null, but when I return the auth->user() to the Vue SPA, I get it correctly. Is there a way to it is setting Auth::user() null after a successfull login? Here's are my api.php (api routes):
route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
route::controller(UserController::class)->group(function () {
route::post('/register', 'register');
route::post('/login', 'login');
route::get('/logout', 'logout');
});
route::resource('book', BookController::class);
route::get('/my_books/{user_id}', [BookController::class, 'myBooks']);
As you can see in the image above, I can get the authenticated user after try login it, here's my login method:
public function login(Request $request)
{
$validate = $request->validate([
'email' => 'required|email',
'password' => 'required'
]);
if ($validate) {
$credentials = $request->only('email', 'password');
return Auth::attempt($credentials)
? Auth::user() :
response()->json('No se ha podido iniciar sesiĆ³n', 500);
}
return response()->json($validate->errors, 422);
}
But when I'm going to store a new book, I get the following error:
Here's the error, when I try to use the auth()->user() method to get the logged in user's id:
public function store(Request $request)
{
$validate = $request->validate([
'title' => 'required',
'genre' => 'required'
]);
if ($validate) {
$book = Book::create([
'title' => $request->title,
'author' => $request->author,
'genre' => $request->genre,
'subgenre' => $request->subgenre,
'opinion' => $request->opinion,
]);
$user = User::find(auth()->user()->id);
if ($request->cover) {
$this->uploadImage($request, 'cover', $book);
}
$user->books()->save($book);
return new BooksResource($book);
}
I don't know why it's happening, and I'd like any idea or possible solution. Thanks in advance:
From laravel 9 documentation
// Get the currently authenticated user's ID...
$id = Auth::id();
Also, you should describe your
route::get('/my_books/{user_id}', [BookController::class, 'myBooks']);
route before resource route.
I guess, you dont need this assign $user = User::find(auth()->user()->id); just use auth()->user
To get the Authenticated user, put the book route inside the auth:sanctum middleware.
I'm trying to register a user in my application and log him in automatically after successfully registering.
What i'm doing:
Sending an HTTP request from the front-end using axios:
register() {
this.loading = true
axios.post('/api/v1/list/register', {
email: this.data.email,
password: this.data.password
}).then((re) => {
this.loading = false
})
}
Back-end controller:
public function register() {
$data = request()->validate([
'email' => ['required', 'string', 'email', 'unique:users'],
'password' => ['required', 'string', 'min:7',],
]);
$user = User::create([
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
Auth::login( $user );
return response()->json([
'user' => Auth::user(),
]);
}
The user get's registered successfully and the server returns the user just fine, although when i refresh the page Auth::check() returns false as a result to display the register page again
<list-property :auth="{{ json_encode(Auth::check()) }}"></list-property>
#if(!Auth::check())
<login-dialog></login-dialog>
#endif
Routes web.php file
Route::get('/list-property', [App\Http\Controllers\MainController::class, 'listProperty']);
I used FILESYSTEM_DRIVER file and database, both had the same issue, what could be the problem?
For anyone who might be experiencing the same issue, the registration was happening through an API route which is incorrect, API routes are stateless, i moved the registration method inside web.php and it worked just fine.
I am using the code below to create a user in Laravel. When I log in with this user, it does not appear to be "authenticated" (even though the ID, password, and tenanted information has been entered correctly). Authenticated users go to a "home" page. This just goes back to the login page.
I noticed that when the user was created the "remember_token" of the "user" table was not filled out.
How can I fill out this field? How can I fix this so that users created using PHP are authenticated?
TIA
$user = User::create([
'name' => $contractor->getFirstName() . ' ' . $contractor->getLastName(),
'email' => $contractor->getAsgnLogonID(),
'password' => bcrypt($contractor->getAsgnPassword()),
'tenantid' => $TENANTREFNO,
'wavemakerid'=> $contractor->getKeyID(),
]);
Here is the web.php file:
Route::get('/', function () {
return redirect()->route('login.showform');
});
Route::post('/login/custom', [
'uses' => 'Auth\LoginController#login',
'as' => 'login.custom'
]);
Route::get('/login/showform', [
'uses' => 'Auth\LoginController#showLoginForm',
'as' => 'login.showform'
]);
Route::get('/home', 'HomeController#index');
Route::get('/logout', 'Auth\LoginController#logout');
Route::get('/dashboard', 'DashboardController#index');
Auth::routes();
I made the changes below and was able to have the user logged in:
if ( $password == $local_password )
{
Auth::login($user);
return redirect('/home');
}
I need to send an email after a new user is created.
But I don't know how to return to the home page without getting an error.
This is what I am doing right now.
User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'phone' => bcrypt($data['phone']),
'confirmation_code' => str_random(30),
]);
Email_function();
if (Auth::attempt(['email' => $data['email'], 'password' => bcrypt($data['password']) ])) {
// Authentication passed...
return redirect('/');
}
I keep getting this as my error message.
SErrorException in SessionGuard.php line 439:
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given, called in /Applications/XAMPP/xamppfiles/htdocs/sniddl/vendor/laravel/framework/src/Illuminate/Foundation/Auth/RegistersUsers.php on line 63 and defined
Edit:
changed the title to reflect the answer.
Here is a modified create function with an added email function for your register controller
Make sure Request is included in the pages top with namespaces being used:
use Illuminate\Http\Request;
Change the create function in your controller:
protected function create(Request $data)
{
$user = new User;
$user->name = $data->input('name');
$user->username = $data->input('username');
$user->email = $data->input('email');
$user->password = bcrypt($data->input('password'));
$user->phone = bcrypt($data->input('phone'));
$user->confirmation_code = str_random(60);
$user->save();
if ($user->save()) {
$this->sendEmail($user);
return redirect('VIEWPATH.VIEWFILE')->with('status', 'Successfully created user.');
} else {
return redirect('VIEWPATH.VIEWFILE')->with('status', 'User not created.');
}
}
Create the sendEmail function in the same controller that will use Laravels built in email. Make sure you create and your HTML email:
public function sendEmail(User $user)
{
$data = array(
'name' => $user->name,
'code' => $user->confirmation_code,
);
\Mail::queue('EMAILVIEWPATH.HTMLEMAILVIEWFILE', $data, function($message) use ($user) {
$message->subject( 'Subject line Here' );
$message->to($user->email);
});
}
NOTE:
Your going to need to update the VIEWPATH.VIEWFILE and EMAILVIEWPATH.HTMLEMAILVIEWFILE at a minimium in the examples above.
Check the repos below for CONTROLLER :
https://github.com/laravel/laravel/blob/master/app/Http/Controllers/Auth/RegisterController.php
https://github.com/jeremykenedy/laravel-auth/blob/master/app/Http/Controllers/Auth/AuthController.php
REGISTER VIEW(blade) EXAMPLE
https://github.com/jeremykenedy/laravel-auth/blob/master/resources/views/auth/register.blade.php
EMAIL VIEW THAT RECEIVES VARIABLES:
https://github.com/jeremykenedy/laravel-auth/blob/master/resources/views/emails/activateAccount.blade.php
Ok so it turns out, by setting User::create as a variable it allows you to login in the user by returning the variable. Like this.
$user = User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'phone' => bcrypt($data['phone']),
'confirmation_code' => str_random(30),
]);
Email_function();
return $user;
I have a registration form and it was working until it just didn't. I am sure I did something with the code because I am new to laravel 4 so I am unable to identify my wrong doing. Now I am getting
This webpage has a redirect loop.
This is the route file:
Route::get('/','MainController#index');
Route::get('/login', 'MembersController#login');
Route::get('/signup', 'MembersController#signup');
/*handled by controller to register the user that signed up*/
Route::get('/register', 'MembersController#register');
/* Handle authenticating a user when loggin in*/
Route::post('register', array(
'uses' => 'MembersController#register',
'as' => 'members.register'
));
and this is the form opening:
#section('content')
{{ Form::open(array('route' => 'members.register')) }}
......
{{ Form::close() }}
#stop
and this is the validation where if there is an error, it used to redirect to the sign-up page again and show them (and it did until it broke)
public function register()
{
$rules = array(
# place-holder for validation rules
'firstname' => 'Required|Min:3|Max:40|Alpha',
'lastname' => 'Required|Min:3|Max:40|Alpha',
'email' => 'Required|Between:3,64|Email|Unique:users',
'country' => 'Required',
'password' =>'Required|AlphaNum|Between:7,15|Confirmed',
'password_confirmation'=>'Required|AlphaNum|Between:7,15'
);
/*Create new user if no user with entered email exists. Use validator to ensure all fields are completed*/
$user = new User;
$validator = $this->validate(Input::all(), $rules);
if ($validator->fails())
{
return Redirect::to('register')->withErrors($validator);
}else{
echo "Success";
}
}
Thanks for the help :)
Change the following line
return Redirect::to('register')->withErrors($validator);
with this
return Redirect::back()->withInput()->withErrors($validator);
You are calling the route register infinite times.
Remove this route as well. You only need post route.
/*handled by controller to register the user that signed up*/
Route::get('/register', 'MembersController#register');