Laravel passport doesn't create User - php

I'm trying to register a user via HTTP POST request with PHP Laravel.
Here is my AuthController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\User;
use Illuminate\Support\Facades\Validator;
class AuthController extends Controller
{
public $successStatus = 200;
public function register(Request $request)
{
$request->validate([
'name' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string|confirmed'
]);
$user = new User([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password)
]);
$user->save();
$message['success'] = 'Created Account Successfully';
return response()->json([
'message' => $message
], 201);
}
public function login(Request $request){
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string'
]);
$credentials = request(['email', 'password']);
if(Auth::attempt($credentials)){
$user = Auth::user();
$message['token'] = $user->createToken('MyApp')->accessToken;
$message['token_type'] = 'Bearer';
$message['experies_at'] = Carbon::parse(Carbon::now()->addWeeks(1))->toDateTimeString();
$message['success'] = 'Logged in successfully';
return response()->json(['message' => $message], $this->successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
}
And my routes/api.php:
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
Route::post('/users', [AuthController::class, 'register']);
When I send a POST request to http://localhost:8080/api/users/ with name,email and passport parameters, it returns 200 response instead of 201. And it's showing the index page of Laravel, not the response. I checked the database, and user is not created.
Can you help me with what I'm missing?

You could try to change the way you do the route. For exemple:
Route::post('users', 'App\Http\Controllers\UsersController#register');
I dont really get why you do: public $successStatus = 200;
Maybe try to remove this line.

Related

Cannot use object of type Illuminate\Validation\Validator as array

I get the following error in postman while testing the post request for api/register.
"Error: Cannot use object of type Illuminate\Validation\Validator as array in file C:\Users\azzam\laravel-app\azzamnewapi\app\Http\Controllers\AuthController.php on line 25"
Here is my AuthController code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\Models\User;
use Laravel\Sanctum\PersonalAccessToken;
class AuthController extends Controller
{
public function register(Request $request) {
//validation field
$validUser=Validator::make($request->all(), [
'name'=> 'required|string',
'email'=> 'required|email',
'password'=> 'required|string',
]);
//create user
$user= User::create([
'name'=> $validUser['name'],
'email'=> $validUser['email'],
'password'=> bcrypt($validUser['password']),
]);
//response
return response([
'user'=> $user,
'token'=> $user->createToken('secret')->plainTextToken,
], 200);
}
public function logout(Request $request) {
//user
$user= User::find(PersonalAccessToken::findToken(explode(' ',$request->header('Authorization'))[1])->tokenable_id);
//delete token
$user->tokens()->delete();
//reponse
return response([
'message'=> 'logout success',
], 200);
}
}
can anyone please tell me where is the mistake, and how to see the $validUser variable? ThankYou.
$validUser=Validator::make is a validator instance.
To validate and get the validated input you can do:
$validUser = $request->validate([
'name'=> 'required|string',
'email'=> 'required|email',
'password'=> 'required|string',
]);
If you must use a manually created validator instance you can do:
$validUser = Validator::make($request->all(), [
'name'=> 'required|string',
'email'=> 'required|email',
'password'=> 'required|string',
])->safe()->all();
These should work with Laravel 8+

Auth::attempt always return false even with proper input

Here are the facades I used
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
I've successfully created user signup page with hashed password using bcrypt.
//Get singnup view
public function getSignup()
{
return view('user.signup');
}
//Process signup
public function postSignup(Request $request)
{
$this->validate($request, [
'email' => 'email|required|unique:users',
'password' => 'required|min:4'
]);
$user = new User([
'email' => $request->input('email'),
'password' => bcrypt($request->input('password')),
]);
$user->save();
return redirect()->route('product.index');
}
And now I'm stuck at the signin page. The Auth::attempt always return false. I even tried to store a plain password in my database and signin without bcrypt but it still returned false. I have no idea where I'm wrong right now.
//Get signin view
public function getSignin()
{
return view('user.signin');
}
//Process signin
public function postSignin(Request $request)
{
$this->validate($request, [
'email' => 'email|required',
'password' => 'required|min:4'
]);
$credentials = array(
'email' => $request->input('email'),
'password' => bcrypt($request->input('password'))
);
if(Auth::attempt($credentials))
{
return redirect()->route('user.profile');
}
return redirect()->route('product.index');
}
You don't need bcrypt() in Auth::attempt(). Remove it and try again.
In config\auth, change guard driver setting is set to api.
'defaults' => [
'guards' => 'api',
'passwords' => 'users'
]
But Laravel doesn't support attempt() function with guard api. Thus, you should use some packages like Passport (You can reference here)
Or simplier, just configure you guard driver with Auth::guard('api')->attempt($credentials)
Hope this solve your problem.

Laravel API: The POST method is not supported for this route. Supported methods: GET, HEAD

I am sending a post request to http://localhost/projects/webdevlist/public/api/register and getting the 405 error:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The POST method is not supported for this route. Supported methods: GET, HEAD.
routes\api.php:
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('/register', 'Api\AuthController#register');
Api\AuthController.php:
<?php
namespace App\Http\Controllers\Api;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|max:55',
'email' => 'required|email',
'password' => 'required|confirmed'
]);
$user = User::create($validatedData);
$accessToken = $user->createToken('token')->accessToken;
return response(['user' => $user, 'access_token' => $accessToken]);
}
}
If I remove the form validation then I can do post requests just fine and return a result in postman like this.
<?php
namespace App\Http\Controllers\Api;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function register(Request $request)
{
return response()->json([
$request->name,
$request->email,
$request->password,
]);
}
}
But something is wrong with my validation. Why does the validation cause me to no longer be able to accept POST requests?
Here is my POST request:
The problem with your validation is the password field.
Your rule say that it need to be required and confirmed, but confirmed against which field?
You need to add a field with name password_confirmation your view, if not added yet.
<input type="password" name="password_confirmation" />
And then add a new rule for password_confirmation field:
$validatedData = $request->validate([
'name' => 'required|max:55',
'email' => 'required|email',
'password' => 'required|confirmed',
'password_confirmation' => 'required'
]);

Call to undefined relationship [] on model []

I have made hasOne relationship in my Model and it is working fine with following query in driver controller:
$drivers = Driver::with('vehicleInfo')->first()->toArray();
Driver Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Driver extends Model
{
// from_location_id
public function vehicleInfo()
{
return $this->hasOne('App\Vehicle','id','vehicle_id');
}
}
But when I try to use same code in AuthController which is generated by Laravel Auth it is giving me error of undefined relationship.
I have included model in AuthController. Which is as follows:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Carbon\Carbon;
use App\User;
use App\Role;
use App\Driver;
class AuthController extends Controller
{
public function login(Request $request)
{
$request->validate([
'mobile' => 'required|string',
'password' => 'required|string',
'remember_me' => 'boolean'
]);
$credentials = request(['mobile', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
// print_r($user);
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
$user_details = User::find($user->id);
if($user_details->actual_user_id>0){
// find driver details
// var_dump(Driver::with('vehicleInfo'));
$driver_details = Driver::with('vehicleInfo')->first()->toArray();
// var_dump($driver_details);
}else{
$driver_details = "";
}
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString(),
'user_details'=>$user_details->toArray(),
'driver_details'=>$driver_details
]);
}
}
My relationship is public.
Please help.

Auth::attempt() always returns false for default brand new installation

I tried lot to search about the problem. I couldn't find any solution. Please help me to understand what i am doing wrong.
I am attaching the code:
UserController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
public function signup(Request $request){
$this->validate($request,[
'name' => 'required',
'email' => 'required|unique:users',
'password' => 'required'
]);
$user = new User([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => bcrypt($request->input('password ')),
]);
$user->save();
return response()->json([
'state' => 'success',
'message' => 'User created.'
],201);
}
public function signin(Request $request){
$credentials = $request->only('email', 'password');
dd(Auth::attempt($credentials));
if (!$token = $this->guard()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
}
And i have routes in api.php
Route::prefix('user')->group(function () {
Route::post('signup', 'UserController#signup');
Route::post('signin', 'UserController#signin');
});
I have
I have this in database
I sent the below json to signup first, but then when i sent to signin i am getting failed.
{
"name":"ironman",
"email":"ironman#yahoo.com",
"password":"avengers"
}
This is a brand new installation of laravel 5.4 (same with 5.5), Using detailt User migration and model came with it.
When i tried to diagnose the problem myself, i found that the password_very is returning false all the time in Auth package.
I am using default password field, hashing it while creating users as other similar questions answered.
I am using php artisan serv.
I am using postman to send this request.
Please help,
This is pulling null from the request:
$request->input('password '); // notice the space
'password' => bcrypt($request->input('password ')),
You probably did not intend to put a space at the end of the input name:
$request->input('password'); // no space
'password' => bcrypt($request->input('password')),

Categories