How to redirect after auth in Laravel? - laravel

When I authorize in Laravel 5.3 I redirect to /home page.
I tried to change this on: protected $redirectTo = '/order'; in file LoginController.
But It does not work, I am redirected on home still.

In my UserController.php , I hope email and passwords are the things you use for user signin.
public function userSignIn(Request $request)
{
$this->validate($request,[
'email' => 'required|email',
'password' => 'required'
]);
if(Auth::attempt(['email'=>$request['email'],'password'=>$request['password']])){
return redirect()->route('order');
}
return redirect()->back();
}
You must have a route for order in your route.php file.

Related

Laravel 9: Auth::user() / auth()->user() null after successfull login

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.

Laravel Sanctum API identify user that is trying to post a Note

So I'm new to Laravel and I've made Login/Signup page to work with React SPA and Laravel Backend, the problem is i don't know now to post to database only for that user, I mean to add a note for that user, How can i do that, how the backend will know that, what is method around that?
Laravel Sanctum provides middlewares to authenticate the requests coming to a route. For that, first, you should validate the user-credentials and generate the token as specified here in the doucmentation.
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
Route::post('/sanctum/token', function (Request $request) {
$request->validate([
'email' => 'required|email',
'password' => 'required',
'device_name' => 'required',
]);
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
return $user->createToken($request->device_name)->plainTextToken;
});
This route validates the user credentials and creates a token. You should include this token in the subsequent requests.
Then protect your routes by including the auth:sanctum middleware.
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Now the $request->user() should return the current authenticated user.
Also read about SPA-Authentication.
https://laravel.com/docs/8.x/sanctum#spa-authentication

Laravel route always not defined although it is declared

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

Auth Issue when upgrading from Laravel 5.2 to Laravel 5.3

I have following the official guide to upgrade from laravel 5.2 to laravel 5.3:
https://laravel.com/docs/5.3/upgrade#upgrade-5.3.0
Because I needed some customizations to the default authentication I have copied the login function to Http\Controllers\Auth\AuthController.php.
Now, when I updated, the `AuthController.php' was divided into several other files.
I have copied the login function to Http\Controllers\Auth\LoginController.php
Now, I am getting the following error when trying to login:
BadMethodCallException in Controller.php line 82:
Method [getCredentials] does not exist.
The login functions below (Might not matter):
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required',
]);
$credentials = $this->getCredentials($request);
// This section is the only change
if (Auth::validate($credentials)) {
$user = Auth::getLastAttempted();
if ($user->active) {
Auth::login($user, $request->has('remember'));
ActivityLog::add("User has successfully logged in.", $user->id);
return redirect()->intended($this->redirectPath());
} else {
return redirect($this->loginPath) // Change this to redirect elsewhere
->withInput($request->only('email', 'remember'))
->withErrors([
'active' => 'This account has been suspended.'
]);
}
}
return redirect($this->loginPath)
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
}
How do I fix this?
This method simply returns the login username (which can be username, email or custom field) and the password from the request data. You can replace the getCredentials() call with this:
$request->only($this->username(), 'password');
NOTE
depending on how you merged the code, the method $this->username() can be also used as $this->loginUsername() in the older version.
Anyone else looking here now the call getCredentials(Response $response) was replaced in 5.3 with credentials(Response $response)

Laravel 5.4 Can't login the user

When I register new User, it logs in, but when I logout and try to login it just redirects me back to login page with custom error message 'Check your credentials again'. I can't figure out what's wrong.
First you are not hashing the password. In RegistrationController change your store() function like this.
use Hash;
class RegistrationContoller extends Controller
{
...
public function store()
{
...
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password) //<-- you were missing this.
]);
}
}

Resources