Here's my DB transaction...
public function store(Request $request)
{
DB::beginTransaction();
try {
$superdoc = SuperDoc::create([
'user_id' => $request->user_id,
'project_name' => $request->project_name,
'status' => $request->status,
'start_date' => $request->start_date,
'end_date' => $request->end_date,
'lines' => $request->lines,
'words' => $request->words,
]);
$lastInsertedId = DB::select('SELECT MAX(ID) FROM super_docs');
} catch (ValidationException $e) {
DB::rollBack();
return redirect()->back();
} catch (\Exception $e) {
DB::rollback();
throw $e;
}
try {
$document = Document::create([
'superD_id' => $request->superD_id,
'url' => $request->url,
'status' => $request->status,
'text' => $request->text,
'doc_type' => $request->doc_type,
'language' => $request->language,
'date' => $request->date,
]);
return response()->json($superdoc, 201);
} catch (ValidationException $e) {
DB::rollBack();
return redirect()->back();
} catch (\Exception $e) {
DB::rollback();
throw $e;
}
DB::commit();
}
I want to set the super_doc to auto-generated last id into the document table superD_id in the above transaction. Can anyone help me?
I don't have Knowledge about laravel bu i can give an idea, After inserting into SuperDoc table , you can get that model and the model will give you the model superD_id , that superD_id you can use in the Document Table.
So i think your code will look like this:
public function store(Request $request)
{
DB::beginTransaction();
try {
$superdoc = SuperDoc::create([
'user_id' => $request->user_id,
'project_name' => $request->project_name,
'status' => $request->status,
'start_date' => $request->start_date,
'end_date' => $request->end_date,
'lines' => $request->lines,
'words' => $request->words,
]);
//$lastInsertedId=DB::select('SELECT MAX(ID) FROM super_docs');
} catch (ValidationException $e) {
DB::rollBack();
return redirect()->back();
} catch (\Exception $e) {
DB::rollback();
throw $e;
}
try {
$document = Document::create([
//$superdoc will have object of saved data which will also have SuperD_id
'superD_id' => $superdoc->superD_id,
'url' => $request->url,
'status' => $request->status,
'text' => $request->text,
'doc_type' => $request->doc_type,
'language' => $request->language,
'date' => $request->date,
]);
return response()->json($superdoc, 201);
} catch (ValidationException $e) {
DB::rollBack();
return redirect()->back();
} catch (\Exception $e) {
DB::rollback();
throw $e;
}
DB::commit();
}
Related
I used Laravel In-App purchase. But I got 422 error after $subscriptionReceipt variable.
This is my code
try {
$user = $request->user();
putenv('GOOGLE_APPLICATION_CREDENTIALS=../storage/keys/my-nourish-plan-app-8d8d0c926954.json');
$subscriptionReceipt = Product::googlePlay()->id($plan_id)->token($receipt)->get();
if ($subscriptionReceipt) {
$latestReceipt = $subscriptionReceipt->getLatestReceiptInfo()[0];
$date = Carbon::now();
Subscription::create(
[
'plan_id' => $request->plan_id,
'is_valid' => 1,
'product_id' => $latestReceipt->getProductId(),
'package_id' => $latestReceipt->getOriginalProductId(),
'transaction_id' => $latestReceipt->getTransactionId() ?? 0,
'start_date' => Carbon::parse($latestReceipt->getPurchaseDate()->toDateTime())->format('Y-m-d'),
'end_date' => Carbon::parse($latestReceipt->getExpiresDate()->toDateTime())->format('Y-m-d'),
'user_id' => $user->id,
'free_plans_month' => $date->month,
'free_plans_availability' => 1
]
);
return response()->apiSuccess(null, 'Subscription added!');
}
return response()->apiError('Receipt verification failed');
} catch (\Exception $e) {
Log::error($e);
return response()->apiError('Something went wrong please try again');
}
i'm trying this updateorcreate method and for some reason id does not insert nothing into database, here is my code example, it enters into catch but it does not display any error msg.
public function insertFacturiFluxFurnizor(Request $request)
{
$user = auth()->user();
$idFluxReceptie = $request->input('idFluxReceptie');
$facturi = $request->input('facturi');
try {
foreach ($facturi as $factura) {
$facturiWms = FacturiWms::updateOrCreate([
'codFactura' => $factura['codFactura']
], [
'fluxReceptie' => $idFluxReceptie,
'idFurnizor' => $factura['idFurnizor'],
'fiscalId' => $factura['fiscalId'],
'codFactura' => $factura['codFactura'],
'dataFactura' => $factura['dataFactura'],
'userId' => $user->userId
]);
}
return response()->json(['facturiWms' => $facturiWms, 'message' => 'CREATED'], 201);
} catch (\Exception $e) {
return response()->json(['message' => $e], 409);
}
}
}
I wish that laravel throw an exception on this "General error: 1364 Field 'author_id' doesn't have a default value" does not throw an exception instead this return the jsonresponse as expected if has succeeded...🤔 How can I have an Exception on this error ?
public function store(StageRequest $request): JsonResponse
{
$validatedData = $request->validated();
$stage = new Stage();
try {
//Stage::create($validatedData);
$stage->fill($validatedData);
if ($stage->save()) {
return response()->json([
'result' => 'success insert',
'id' => $validatedData['id'],
]);
} else {
return response()->json([
'result' => 'error',
'id' => $validatedData['id'],
]);
}
} catch (\Exception $e) {
report($e);
return response()->json([
'result' => 'error',
'message' => $e->getMessage(),
'id' => $request->input('id'),
]);
}
}
You can catch PDO Exception, like :
try
{
//write your codes here
}
catch(\PDOException $e)
{
return response()->json([
'result' => 'error',
'message' => $e->getMessage(),
'id' => $request->input('id'),
]);
}
I'm using Laravel and JWT token for develop backend APIs for frontend developers.
I put status(active , inactive) column in database
If user status is inactive then restrict him to using the app.
part of login function which gives token on active user:
if ($user->status == 'active') {
return response()->json(
['data' => ['token' => $token, 'message' => 'Login successfully.', 'status' => true, 'user' => $user]],
200
);
}
if ($user->status == 'inactive') {
return response()->json(
['data' => ['token' => '', 'message' => 'User is inactive.', 'status' => false]],
200
);
}
my middleware:
public function handle($request, Closure $next)
{
try {
$user = JWTAuth::parseToken()->authenticate();
} catch (Exception $e) {
if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException) {
return response()->json(['data' => ['message' => 'Token is Invalid.', 'status' => false]],
200);
} else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException) {
return response()->json(['data' => ['message' => 'Token is Expired.', 'status' => false]], 200);
} else {
return response()->json(['data' => ['message' => 'Authorization Token not found.', 'status' => false]], 200);
}
}
return $next($request);
}
You need to write another Middleware to check that user is active.
Put it after auth middleware and return 403 when !$user->is_active.
For check the user is Active or inactive, It's better to check it in another middleware but if you want to check user active or inactive in this middleware. The simplest way to get it:
public function handle($request, Closure $next)
{
try {
$user = JWTAuth::parseToken()->authenticate();
if ($user->status == 'inactive') {
return response()->json(['data' => ['token' => '', 'message' => 'User is inactive.', 'status' => false]], 403);
}
} catch (Exception $e) {
if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException) {
return response()->json(['data' => ['message' => 'Token is Invalid.', 'status' => false]],
200);
} else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException) {
return response()->json(['data' => ['message' => 'Token is Expired.', 'status' => false]], 200);
} else {
return response()->json(['data' => ['message' => 'Authorization Token not found.', 'status' => false]], 200);
}
}
return $next($request);
}
when i am create and update record then "Serialization of 'Closure' is not allowed" this error occurs
public function update(Request $request, $id){
try{
$validatedData = Validator::make($request->all(),[
'amount' => 'required',
]);
if($validatedData->fails())
{
return redirect()->back()->with(['add_error_message' => $validatedData]);
}
$class_id = $request->class;
$enroll_id = $request->enroll_type;
$payment_id = $request->payment_type;
$amount = $request->amount;
ClassWiseFee::where('id', $id)
->update([
'class_id' => $class_id,
'enrollment_id' => $enroll_id,
'payment_id' => $payment_id,
'amount' => $amount,
]);
return redirect()->back()->with(['update_success' => 'Record update successfully']);
}catch (\Exception $e){
return redirect()->back()->with(['exception_error' => $e]);
}
}