laravelapifilterjsonapi-resources

Sort data in api resource by an item


I have this database structure :

public function up()
    {
        Schema::create('skills', function (Blueprint $table) {
            $table->id();
            $table->string('name',50);
            $table->integer('level');
            $table->string('description',100);
            $table->string('rule',100)->default('main'); // main | other | lang
            $table->timestamps();
        });
    }

Now i want sort this data by rule in laravel api resource

For example when i call my api route it's should return this :


data{

main [
   0 => {
       'name' : 'name',
       'level' : 'level',
       'description' : 'description',
    }
],
other [
   0 => {
       'name' : 'name',
       'level' : 'level',
       'description' : 'description',
    }
],
lang [
   0 => {
       'name' : 'name',
       'level' : 'level',
       'description' : 'description',
    }
],

}

So what should i do for handle it

My database structure is good?

ResourceCollection better than resource?

Thank you


Solution

  • You should add index for rule field for better query performance. https://laravel.com/docs/8.x/migrations#indexes

    I think you need to use orderBy method of QueryBuilder to handle it. https://laravel.com/docs/8.x/queries#ordering