V
V
Vladimir Singhtlov2018-07-24 19:51:02
Laravel
Vladimir Singhtlov, 2018-07-24 19:51:02

How to synchronize laravel requests?

For example, there are User, Key, Prize models.
In the binding table Reward of the user_id, key_id, prize_id fields, every 10 is given a prize, but no more than 3 per user.
In the case of folding into a transaction, one of them can be completed faster and then the user who sent the request earlier will not receive a prize.

public function index(Request $request)
    {

        $validator = Validator::make(
            $request->all(),
            $this->rules('index'));

        if ($validator->fails()) {
            return response()->json(
                [
                    "message" => "Validation Errors",
                    "errors" => $validator->errors()
                ], 500);
        }

        $data = DB::transaction(function() use ($request)
        {

            $user = User::find($request->user_id);

            $prize_count = $user->prizes()->count();

            if ($prize_count >= 3) {
                return response()->json([
                    "message" => "Register Code Error",
                    "errors" => 'Limit is exceeded'
                ], 500);
            }

            $key = Key::where('name', $request->code)->first();

            $reward = new Reward([
                'user_id' => $user->id,
                'key_id' => $key->id
            ]);
            $reward->save();

            $rewards = Reward::orderBy('created_at', 'desc')->take(10)->get();



            if ($rewards->where('prize_id', null)->count() < 10) {

                return response()->json([
                    "message" => "Registered code"
                ]);

            } else {

                $random_prize = Prize::inRandomOrder()->first();
                $reward->prize()->associate($random_prize);
                $reward->save();
                sleep(100);
                return response()->json([
                    "message" => "Won",
                    "prize" => $random_prize
                ]);
            }


        });


        return $data;


    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question