I'm New in Laravel but I know flutter here what I am trying to achieve I have created a Laravel Api where token is generated by sanctum and I getting the token properly when I test on postman but when I try this from flutter project I get the token but i get this error
{ "message": "Unauthenticated." }
here is my laravel function in controller
`\public function store(Request $request) { $validator = Validator::make($request->all(), [ 'phone_no' => 'required|digits:10', 'name' => 'sometimes|string|nullable', // Allow empty name 'address' => 'sometimes|string|nullable', // Allow empty address 'longitude' => 'sometimes|string|nullable', // Allow empty longitude and latitude 'latitude' => 'sometimes|string|nullable', // Allow empty longitude and latitude 'accuracy' => 'sometimes|string|nullable', // Allow empty longitude and latitude 'referby_coupon' => 'sometimes|string|nullable', // Allow empty referby_coupon ]); // Check for existing user with the same phone number $user = UserModel::where('phone_no', $request->phone_no)->first();
if ($validator->fails()) {
return response()->json([
'status' => 422,
'errors' => $validator->messages()
], 422);
} else {
if ($user) {
$user->name = $user->name === 'new' ? '' : $user->name;
$user->address = $user->address === 'new' ? '' : $user->address;
$user->longitude = $user->longitude === 'new' ? '' : $user->longitude;
$user->latitude = $user->latitude === 'new' ? '' : $user->latitude;
$user->accuracy = $user->accuracy === 'new' ? '' : $user->accuracy;
$user->referby_coupon = $user->referby_coupon === 'new' ? '' : $user->referby_coupon;
$token = $user->createToken($request->id)->plainTextToken;
return response()->json([
'status' => 422,
'message' => 'User already exists',
'token' => $token,
'data' => $user
], 422);
} else {
// Generate random coupon
$coupon = $this->generateRandomCoupon();
$user = UserModel::create([
'id' => $request->id,
'name' => $request->name,
'phone_no' => $request->phone_no,
'address' => $request->address,
'longitude' => $request->longitude,
'latitude' => $request->latitude,
'accuracy' => $request->accuracy,
'own_coupon' => $coupon, // Insert the generated coupon here
'referby_coupon' => $request->referby_coupon,
]);
if ($user) {
$token = $user->createToken($request->id)->plainTextToken;
return response()->json([
'status' => 200,
'token' => $token,
'message' => 'User Created Successfully'
], 200);
} else {
return response()->json([
'status' => 500,
'message' => 'Something went wrong'
], 500);
}
}
}
}
private function generateRandomCoupon($length = 4) { $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $excludedWords = ['CAT', 'DOG', 'SEX','sex', 'FUCK','fuck']; // Add any words you want to exclude here $coupon = '';
do {
$coupon = '';
for ($i = 0; $i < $length; $i++) {
$coupon .= $characters[rand(0, strlen($characters) - 1)];
}
} while (UserModel::where('own_coupon', $coupon)->exists() || in_array($coupon, $excludedWords, true));
return $coupon;
}`
this is model class
`
protected $table = 'users';
<?php
namespace App\Models; use Laravel\Sanctum\HasApiTokens; use Illuminate\Notifications\Notifiable; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Auth\User as Authenticatable; use Laravel\Sanctum\PersonalAccessToken as SanctumPersonalAccessToken;
class UserModel extends Authenticatable { use HasApiTokens, HasFactory, Notifiable;
protected $fillable = [
'id',
'name',
'phone_no',
'address',
'longitude',
'latitude',
'accuracy',
'own_coupon',
'referby_coupon',
];
protected $primaryKey = "id";
public $timestamps = false;
}`
this is my flutter code
Future<void> setData(String name, String address, String phoneNo,
String longitudeLatitude, String referByCoupon) async {
DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyymmddhhmmsskkmm').format(now);
var formData = FormData.fromMap({
'id': formattedDate,
'name': 'new',
'address': 'new',
'phone_no': MyLogin.phoneNoTransfer,
'longitude': 'new',
'latitude': 'new',
'accuracy': 'new',
'own_coupon': "new",
'referby_coupon': referByCoupon.isNotEmpty ? referByCoupon : 'new'
});
try {
Dio dio = Dio(BaseOptions(validateStatus: (statusCode) {
if (statusCode == 422) {
return true;
}
if (statusCode == 200) {
return true;
}
return false;
}));
final response = await dio.post(
options: Options(headers: {
HttpHeaders.contentTypeHeader: "application/json",
}),
'$startUrl/public/api/user',
data: formData,
);
print(response);
print(response.statusCode);
String token = response.data['token'];
if (response.statusCode == 200) {
SharedPreferencesPersonalData().setToken(token);
SharedPreferencesPersonalData().setID(int.parse(formattedDate));
SharedPreferencesPersonalData().setPhoneNo(phoneNo);
} else if (response.statusCode == 422) {
final result = response.data['data'];
print(result);
int apiId = int.parse(result['id'].toString());
String apiPhoneNo = result['phone_no'].toString();
String apiName = result['name'].toString();
String apiAddress = result['address'].toString();
String ownCoupon = result['own_coupon'];
String referByCoupon = result['referby_coupon'];
SharedPreferencesPersonalData().setID(apiId);
SharedPreferencesPersonalData().setPhoneNo(apiPhoneNo);
SharedPreferencesPersonalData().setName(apiName);
SharedPreferencesPersonalData().setAddress(apiAddress);
SharedPreferencesPersonalData().setOwnCoupon(ownCoupon);
SharedPreferencesPersonalData().setReferByCoupon(referByCoupon);
SharedPreferencesPersonalData().setToken(token);
} else {
print(response.statusCode);
}
} catch (e) {
print(e);
}
}
I am excepting the token work properly but its not working and i notices that when I use postman in access token id all column fill but when I use login in flutter tokenable id is 0 and i hosted in hostinger
futter where i am getting error
from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/rOgWz9N
via IFTTT
Aucun commentaire:
Enregistrer un commentaire