Laravel API routes not working with Postman - laravel

My route/api.php has these routes:
Route::post('/signup' , 'UserApiController#signup');
Route::post('/logout' , 'UserApiController#logout');
Route::post('/verify' , 'UserApiController#verify');
but when I'm trying to access from Postman like this, it shows object not found:
localhost/my_webiste/api/signup
here the userapicontroller signup function:
public function signup(Request $request)
{
$this->validate($request, [
'social_unique_id' => ['required_if:login_by,facebook,google','unique:users'],
'device_type' => 'required|in:android,ios',
'device_token' => 'required',
'device_id' => 'required',
'login_by' => 'required|in:manual,facebook,google',
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'mobile' => 'required',
'password' => 'required|min:6',
]);
try{
$User = $request->all();
$User['payment_mode'] = 'CASH';
$User['password'] = bcrypt($request->password);
$User = User::create($User);
return $User;
} catch (Exception $e) {
return response()->json(['error' => trans('api.something_went_wrong')], 500);
}
}
here the postman output of post request of localhost/mywebsite/api/signup :
<title>Object not found!</title>
<link rev="made" href="mailto:postmaster#localhost" />
<h1>Object not found!</h1>
The requested URL was not found on this server.
If you entered the URL manually please check your
spelling and try again.

Make sure, in your postman, to add the header accept = application/json.

Your code is correct. It seems like you are missing public from url
localhost/my_webiste/public/api/signup

Related

error getting a user existing in laravel sanctum

I have a error, I'm using sanctum and I want to check that the email does not exist
the if returns an empty array but the if is satisfied because it returns true
$mail = $request->input(['email']);
if ($search = User::where('email', $mail)->get()) {
return response()->json(['msg' => 'account already exist'], 409);
} else {
$validate = $request->validate([
'name' => 'required|string|',
'email' => 'required|string',
'password' => 'required|string'
]);
}
any solution?
Why not use the Laravel validation since this looks more like validation, so something like:
$request->validate([
'name' => 'required|string|',
'email' => 'required|string|email|unique:users,email',
'password' => 'required|string'
]);
with this you don't need to do an if else. You can check the Laravel docs on https://laravel.com/docs/8.x/validation#introduction for more details

How can i pass only one message for all fields

This is code of register function which generate error of success and failure.
public function register(Request $request) {
$validator = Validator::make($request->all(),
[
'user_type' => 'required',
'fname' => 'required',
'lname' => 'required',
'dob' => 'required',
'phone' => 'required',
'gender' => 'required',
'uname' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['failed'=>$validator->errors()], 401); }
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('AppName')->accessToken;
$success['status'] = true;
$success['data'] = [$user];
$success['message'] ="User created successfully!";
// return response()->json([
// "message" => " record created"
// ], 201);
return response()->json($success, $this->successStatus);
}
This is my output
1.All error message show in one line..This is my main point..But i want to actually this message of This image...How can i do that?
2.Second thing in API if any user put same email id api give json error not laravel error..
Try this:
return response()->json(['status'=> False, 'msg' => 'This is not successful'], 401);
You can pass custom json in response instead of validator response.
For checking if email exists update the validation like this:
'email' => 'required|email|unique:users,email',
where users is your table name and email is your column name
You just need to replace your code
if ($validator->fails()) {
return response()->json(['failed'=>$validator->errors()], 401);
with
if ($validator->fails()) {
return response()->json(['status'=> 'False', 'msg' => 'This is not sccessfully'], 401);

Laravel 5.3 OAuth token error in REST API

When I am trying to register a user from mobile, that data is inserting in the users table but not in oauth_clients. It should upload at the same time.
When I try to login, it shows oauth/token 401 error
Here are my routes:
Route::post('/register' , 'ProviderAuth\TokenController#register');
Route::post('/oauth/token' , 'ProviderAuth\TokenController#authenticate');
This is my register function, which is in TokenConrtoller:
public function register(Request $request)
{
$this->validate($request, [
'device_id' => 'required',
'device_type' => 'required|in:android,ios',
'device_token' => 'required',
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'email' => 'required|email|max:255|unique:providers',
'mobile' => 'required',
'password' => 'required|min:6|confirmed',
]);
try{
$Provider = $request->all();
$Provider['password'] = bcrypt($request->password);
$Provider['status'] = 'approved';
$Provider = Provider::create($Provider);
ProviderDevice::create([
'provider_id' => $Provider->id,
'udid' => $request->device_id,
'token' => $request->device_token,
'type' => $request->device_type,
]);
return $Provider;
} catch (QueryException $e) {
if ($request->ajax() || $request->wantsJson()) {
return response()->json(['error' => 'Something went wrong, Please try again later!'], 500);
}
return abort(500);
}
}
This is my authenticate method:
public function authenticate(Request $request)
{
$this->validate($request, [
'device_id' => 'required',
'device_type' => 'required|in:android,ios',
'device_token' => 'required',
'email' => 'required|email',
'password' => 'required|min:6',
]);
Config::set('auth.providers.users.model', 'App\Provider');
$credentials = $request->only('email', 'password');
try {
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'The email address or password you entered is incorrect.'], 401);
}
} catch (JWTException $e) {
return response()->json(['error' => 'Something went wrong, Please try again later!'], 500);
}
$User = Provider::with('service', 'device')->find(Auth::user()->id);
$User->access_token = $token;
$User->currency = Setting::get('currency', '$');
if($User->device) {
if($User->device->token != $request->token) {
$User->device->update([
'udid' => $request->device_id,
'token' => $request->device_token,
'type' => $request->device_type,
]);
}
} else {
ProviderDevice::create([
'provider_id' => $User->id,
'udid' => $request->device_id,
'token' => $request->device_token,
'type' => $request->device_type,
]);
}
return response()->json($User);
}
I think you should register in JWT auth Like
$token = JWTAuth::fromUser($user);
after Register User
Check this Link for more information
https://blog.pusher.com/laravel-jwt/

Laravel 5.5 Api Registration issue

I have been trying to get this api up and running and keep on experiencing this error when I test in Postman.
1. api.php
Route::group(['middleware' => ['api','cors']], function () {
Route::post('auth/register', 'Auth\RegisterController#create');
});
2. RegisterController
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}}
Postman configuration set to Post, the body is set to raw and JSON(application/json) Below is the postman json code.
{
"name": "Walter White",
"email": "wwhite#someemaildomain.net",
"password": "testpassword"
}
Below is the error
Too few arguments to function App\Http\Controllers\Auth\RegisterController::create(), 0 passed and exactly 1 expected in file C:\xampp\examplestuff
In order to fix your registration you should change your route definition to:
Route::group(['middleware' => ['api','cors']], function () {
Route::post('auth/register', 'Auth\RegisterController#register');
});
I assume your RegisterController is using the trait RegistersUsers. This trait is providing the register method, which is using the RegisterController::create method to create the new user itself.
Pass Request to your create function like:
protected function create(Request $request){...
and access your data like this:
$request->name
you have to do validation also plz check below answer
protected function create(Request $request)
{
$data = $request->json()->all();
$validator = Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
if ($validator->fails()) {
foreach ($validator->messages()->getMessages() as $field_name => $message){
$messages[] = $message[0];
}
$messages = $messages;
$message = implode(',',$messages);
$response = $messages;
return $response;
}else{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}

Laravel API using JWT Auth Credential (username/email)

I'm using laravel with JWT Auth to connect my laravel project to mobile, this is my api controller at laravel
public function login(Request $request) {
$credentials = $request->only('email', 'password');
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
$user = Sentry::authenticate($credentials, false);
return response()->json([
'code' => '200',
'message' => 'success',
'last_updated' => $user->updated_at->format("Y-m-d\TH:i:s\Z"),
'data' => [
'id' => $user->id,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email,
'username' => $user->username,
'token' => $token
]
]);
}
but how to set the credentials using email or username with this JWT?
If you are using "tymon/jwt-auth" package, then you can just pass the user object to the JWTAuth class and bam!, you can get the JWT token in return which you can use to make user go through the app.
$user = User::where('email', $email)
->orWhere('username', $username)
->first();
$token = null;
if (!$token = JWTAuth::fromUser($get_info)) {
return $this->respondInternalError( 'Can\'t generate the JWT token right now, try again later!', 'object', 400);
}
return response()->json([
'code' => '200',
'message' => 'success',
'last_updated' => $user->updated_at->format("Y-m-d\TH:i:s\Z"),
'data' => [
'id' => $user->id,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email,
'username' => $user->username,
'token' => $token
]
]);
You can login using email or using the following format
public function login(Request $request)
{
//validate incoming request
$this->validate($request, [
'email_phone' => 'required|string',
'password' => 'required|string',
]);
try {
$login_type = filter_var( $request->email_phone, FILTER_VALIDATE_EMAIL ) ? 'email' : 'phone';
// return $login_type;
$credentials = [$login_type => $request->email_phone, 'password'=>$request->password];
if (! $token = Auth::attempt($credentials)) {
return response()->json($this->customResponse("failed", "Unauthorized"), 401);
}
return $this->respondWithToken($token);
} catch(JWTException $e) {
return response()->json($this->customResponse("failed", "An error occured, please contact support.", $user), 500);
}
}

Resources