A
A
Anton2019-06-07 10:46:39
Laravel
Anton, 2019-06-07 10:46:39

How to properly update data in applications on demand?

There is a backend for mobile applications on Laravel which receives a request to update data in json format

'data': [
     {'table': 'Product', 'updated_at': <timestamp>}
  ],

In the backend, all data from the table passed in the request that is fresher than the timestamp specified there updated_at is selected and returned as json
public function handle()
    {
        $requestData = request('data');

        $responseData = [];

        foreach ($requestData as $item) {
            $model = "\\App\\" . $item['table'];
            $updated = $item['updated_at'];

            $collection = $model::where('updated_at', '>', $updated)->get();

            if ($collection->count()) {
                $maxUpdatedAt = $collection->pluck('updated_at')->max();

                $responseData[] = [
                    'updated_at' => $maxUpdatedAt,
                    'table' => $item['table'],
                    'data' => $collection->toArray()
                ];
            }

        }

        $response = ['action' => 'update', 'data' => $responseData];

        return response()->json($response);
    }

The question arises - what to do with a huge number of requests? Caching doesn't seem to work in this case. What solutions are suitable for such tasks? I read about Broadcasting, but this is a slightly different approach and can it be used in this case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Razgelday, 2019-08-22
@Razgelday

You obviously turned somewhere wrong when you started making one query to get data from several tables at once.
1) It is better to stick to the resource approach (RESTful API), then there will be no such problems.
Laravel has built-in methods for implementing a RESTful API, such as resource-controllers ( https://laravel.com/docs/master/controllers#resour...
With a RESTful approach, you will need to make 1 request for each table - this should not cause problems in most cases.If you have a huge number of tables - then most likely you have designed something wrong or you need to consider a different type of database (maybe ClickHouse? )
2) To standardize requests and responses, use https:/ /jsonapi.org/.
There are good packages for this:https://github.com/spatie/laravel-query-builder (backend) and https://github.com/robsontenorio/vue-api-query (JS front, can be used even in ReactNative).
If this is too simple for you, then look towards GraphQL.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question