Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Default or custom sort not working. #88

Closed
sahil-kindlebit opened this issue Jun 9, 2021 · 17 comments
Closed

Default or custom sort not working. #88

sahil-kindlebit opened this issue Jun 9, 2021 · 17 comments

Comments

@sahil-kindlebit
Copy link

sahil-kindlebit commented Jun 9, 2021

I want to fetch records and it works fine, but I want to sort it with a particular column.
so I tried this in my schema -
protected $defaultSort = '-createdAt';

but this is not sorting the records, I also tried with other column names, no luck.

in my controller index function

if I use

 $spaces = $spaces->where('user_id', $user->id);
 $spaces = $spaces->sort('createdAt');

error attached below is received. (where condition works fine, only sort is triggering that error).

I do not want to handle sort from the url like GET /spaces?sort=-createdAt HTTP/1.1 .
Please guide.

image

@lindyhopchris
Copy link
Contributor

That exception message doesn't help. If you look down the stack trace, you'll find that exception is caused by a previous exception. Can you provide details of the first exception in the stack trace, not the last?

@sahil-kindlebit
Copy link
Author

sahil-kindlebit commented Jun 10, 2021

image

Please check here and this is my code.

image

@lindyhopchris
Copy link
Contributor

I can't help you unless you are able to provide the previous exception.

The exception you have taken an image of is not the root cause of the problem. It is originating from here:
https://github.com/laravel-json-api/encoder-neomerx/blob/f41bb36f2fa32e35f41116425a402eaf88abec7d/src/Document.php#L187-L195

As you can see, another exception is causing the problem. It is caught, and re-thrown as the exception you have taken an image of. However, that has a previous exception which will explain what the error is that has caused the problem.

Without seeing the full stack trace - including all previous exceptions there is no way I can help you! Because I need to see the previous exceptions to know what the problem is.

@sahil-kindlebit
Copy link
Author

image
Do you mean this?
this
$this->encodeOptions
returns 0

@lindyhopchris
Copy link
Contributor

No.

I need to see the entire stack trace of the exception. You've only provided part of it.

If you go to the Laravel log in the /storage/logs directory, you should see the exception in the log. But as I have already stated, I don't need just the first exception: the exception you have provided has previous exceptions - and I need to see all of those previous exceptions.

Please provide the entire stack trace - not as an image, as a copy and paste of the stack trace from the Laravel log.

Otherwise there is no way for me to help you, and I'll have to close the issue.

@sahil-kindlebit
Copy link
Author

Sure, here it is - >

[2021-06-11 09:20:06] local.ERROR: Unable to encode compound document. {"userId":1,"exception":"[object] (LogicException(code: 0): Unable to encode compound document. at /home/vagrant/code/vendor/laravel-json-api/encoder-neomerx/src/Document.php:195)
[stacktrace]
#0 /home/vagrant/code/vendor/laravel-json-api/core/src/Core/Responses/Internal/ResourceCollectionResponse.php(86): LaravelJsonApi\Encoder\Neomerx\Document->toJson()
#1 /home/vagrant/code/vendor/laravel-json-api/core/src/Core/Responses/DataResponse.php(115): LaravelJsonApi\Core\Responses\Internal\ResourceCollectionResponse->toResponse()
#2 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Router.php(774): LaravelJsonApi\Core\Responses\DataResponse->toResponse()
#3 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Router.php(761): Illuminate\Routing\Router::toResponse()
#4 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Router.php(695): Illuminate\Routing\Router->prepareResponse()
#5 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\Routing\Router->Illuminate\Routing\{closure}()
#6 /home/vagrant/code/vendor/laravel-json-api/laravel/src/Http/Middleware/BootJsonApi.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#7 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): LaravelJsonApi\Laravel\Http\Middleware\BootJsonApi->handle()
#8 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(50): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#9 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Routing\Middleware\SubstituteBindings->handle()
#10 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php(127): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#11 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php(103): Illuminate\Routing\Middleware\ThrottleRequests->handleRequest()
#12 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php(55): Illuminate\Routing\Middleware\ThrottleRequests->handleRequestUsingNamedLimiter()
#13 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Routing\Middleware\ThrottleRequests->handle()
#14 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php(44): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#15 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Auth\Middleware\Authenticate->handle()
#16 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#17 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Router.php(697): Illuminate\Pipeline\Pipeline->then()
#18 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Router.php(672): Illuminate\Routing\Router->runRouteWithinStack()
#19 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Router.php(636): Illuminate\Routing\Router->runRoute()
#20 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Router.php(625): Illuminate\Routing\Router->dispatchToRoute()
#21 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(166): Illuminate\Routing\Router->dispatch()
#22 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}()
#23 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#24 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.php(31): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle()
#25 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull->handle()
#26 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#27 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php(40): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle()
#28 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Foundation\Http\Middleware\TrimStrings->handle()
#29 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php(27): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#30 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Foundation\Http\Middleware\ValidatePostSize->handle()
#31 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/PreventRequestsDuringMaintenance.php(86): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#32 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance->handle()
#33 /home/vagrant/code/vendor/fruitcake/laravel-cors/src/HandleCors.php(57): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#34 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Fruitcake\Cors\HandleCors->handle()
#35 /home/vagrant/code/vendor/fideloper/proxy/src/TrustProxies.php(57): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#36 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Fideloper\Proxy\TrustProxies->handle()
#37 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#38 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(141): Illuminate\Pipeline\Pipeline->then()
#39 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(110): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter()
#40 /home/vagrant/code/public/index.php(52): Illuminate\Foundation\Http\Kernel->handle()
#41 {main}

[previous exception] [object] (ErrorException(code: 0): asort() expects parameter 2 to be int, string given at /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Collections/Collection.php:1099)
[stacktrace]
#0 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleError()
#1 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Collections/Collection.php(1099): asort()
#2 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Collections/LazyCollection.php(1404): Illuminate\Support\Collection->sort()
#3 /home/vagrant/code/vendor/laravel-json-api/core/src/Core/Resources/ResourceCollection.php(109): Illuminate\Support\LazyCollection->Illuminate\Support\{closure}()
#4 /home/vagrant/code/vendor/laravel-json-api/core/src/Core/Resources/Container.php(107): LaravelJsonApi\Core\Resources\ResourceCollection->getIterator()
#5 /home/vagrant/code/vendor/laravel-json-api/neomerx-json-api/src/Parser/Parser.php(152): LaravelJsonApi\Core\Resources\Container->cursor()
#6 /home/vagrant/code/vendor/laravel-json-api/neomerx-json-api/src/Parser/Parser.php(131): Neomerx\JsonApi\Parser\Parser->parseAsResourcesOrIdentifiers()
#7 /home/vagrant/code/vendor/laravel-json-api/neomerx-json-api/src/Encoder/Encoder.php(191): Neomerx\JsonApi\Parser\Parser->parse()
#8 /home/vagrant/code/vendor/laravel-json-api/neomerx-json-api/src/Encoder/Encoder.php(106): Neomerx\JsonApi\Encoder\Encoder->encodeDataToArray()
#9 /home/vagrant/code/vendor/laravel-json-api/encoder-neomerx/src/CompoundDocument.php(61): Neomerx\JsonApi\Encoder\Encoder->encodeData()
#10 /home/vagrant/code/vendor/laravel-json-api/encoder-neomerx/src/Document.php(193): LaravelJsonApi\Encoder\Neomerx\CompoundDocument->encode()
#11 /home/vagrant/code/vendor/laravel-json-api/core/src/Core/Responses/Internal/ResourceCollectionResponse.php(86): LaravelJsonApi\Encoder\Neomerx\Document->toJson()
#12 /home/vagrant/code/vendor/laravel-json-api/core/src/Core/Responses/DataResponse.php(115): LaravelJsonApi\Core\Responses\Internal\ResourceCollectionResponse->toResponse()
#13 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Router.php(774): LaravelJsonApi\Core\Responses\DataResponse->toResponse()
#14 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Router.php(761): Illuminate\Routing\Router::toResponse()
#15 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Router.php(695): Illuminate\Routing\Router->prepareResponse()
#16 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\Routing\Router->Illuminate\Routing\{closure}()
#17 /home/vagrant/code/vendor/laravel-json-api/laravel/src/Http/Middleware/BootJsonApi.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#18 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): LaravelJsonApi\Laravel\Http\Middleware\BootJsonApi->handle()
#19 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(50): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#20 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Routing\Middleware\SubstituteBindings->handle()
#21 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php(127): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#22 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php(103): Illuminate\Routing\Middleware\ThrottleRequests->handleRequest()
#23 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php(55): Illuminate\Routing\Middleware\ThrottleRequests->handleRequestUsingNamedLimiter()
#24 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Routing\Middleware\ThrottleRequests->handle()
#25 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php(44): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#26 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Auth\Middleware\Authenticate->handle()
#27 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#28 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Router.php(697): Illuminate\Pipeline\Pipeline->then()
#29 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Router.php(672): Illuminate\Routing\Router->runRouteWithinStack()
#30 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Router.php(636): Illuminate\Routing\Router->runRoute()
#31 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Routing/Router.php(625): Illuminate\Routing\Router->dispatchToRoute()
#32 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(166): Illuminate\Routing\Router->dispatch()
#33 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}()
#34 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#35 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.php(31): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle()
#36 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull->handle()
#37 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#38 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php(40): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle()
#39 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Foundation\Http\Middleware\TrimStrings->handle()
#40 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php(27): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#41 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Foundation\Http\Middleware\ValidatePostSize->handle()
#42 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/PreventRequestsDuringMaintenance.php(86): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#43 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance->handle()
#44 /home/vagrant/code/vendor/fruitcake/laravel-cors/src/HandleCors.php(57): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#45 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Fruitcake\Cors\HandleCors->handle()
#46 /home/vagrant/code/vendor/fideloper/proxy/src/TrustProxies.php(57): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#47 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Fideloper\Proxy\TrustProxies->handle()
#48 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#49 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(141): Illuminate\Pipeline\Pipeline->then()
#50 /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(110): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter()
#51 /home/vagrant/code/public/index.php(52): Illuminate\Foundation\Http\Kernel->handle()
#52 {main}
"}

@lindyhopchris
Copy link
Contributor

So the error is in your log:

[previous exception] [object] (ErrorException(code: 0): asort() expects parameter 2 to be int, string given at /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Collections/Collection.php:1099)

You should be using the sortBy() collection method:

$spaces->sortBy('createdAt');

That will sort by ascending order.

I don't fully understand why you are sorting in the controller action like that. The $defaultSort property on the schema is working, and fully tested so I know for sure that it works.

If you were putting a $defaultSort property on your schema AND then sorting in the controller action, then obviously the controller action sort will override what the schema has sorted by.

@sahil-kindlebit
Copy link
Author

sahil-kindlebit commented Jun 11, 2021

Hi, Okay.
I updated my code after your answer, now I am using soryByDesc it works fine now.

Also, regarding defaultSort, I have this in my Schema, but sorting doesn't work.

class SpaceSchema extends Schema
{
    protected $defaultSort = '-created_at';
    ...
}

Please guide.

@lindyhopchris
Copy link
Contributor

Firstly, why are you using a custom index action? Why aren't you using the one provided by this package? If it is so you can filter by the current user, you should not need to do that yourself if you correctly follow the guidance in the Authorization chapter, particularly around using an indexQuery() hook:
https://laraveljsonapi.io/docs/1.0/requests/authorization.html#index-filtering

Secondly, on the schema (and as explained in the docs) the default sort uses the JSON:API field names, not the model column names.

Are you 100% sure it shouldn't be:

protected $defaultSort = '-createdAt';

I.e. createdAt not created_at??

Also as already mentioned, if you're using a custom index action and sorting after the schema has done its work, then that will override what is on your schema.

Please:

  1. Remove your custom index action and use the one provided by this package.
  2. Ensure that the JSON:API field name is correct on the schema $defaultSort, i.e. createdAt or created_at.
  3. Make sure that when you send the HTTP request, you do not have a value for the sort parameter. The default sort is only used if the sort parameter is not present in the request. I.e. a ?sort= would prevent the default sort from being applied.

@lindyhopchris
Copy link
Contributor

This issue is taking up a lot of my time, so I need to be clear: default sorting does work, and the tests prove this is case. It's tested extensively in the laravel-json-api/eloquent package and I've just pushed a test to the laravel-json-api/laravel package that proves it's working there. It is also working in the large production application that I'm using the package in.

At the moment therefore I have no reason to suspect there's a problem with this package, and you need to look carefully at what you're doing in your application that could be causing the problem. I can't help you with that - because I can't debug what's going on in your application.

@sahil-kindlebit
Copy link
Author

sahil-kindlebit commented Jun 11, 2021

I understand, but the defaultSort do not work for me, which is why I had to use the custom function.
for the custom query I can use which you referred from the documentation, but for the default sort,

I tried with "-createdAt", "-id", "-created_at", and it is not working for me.

I have also removed the index function and used Package's use Actions\FetchMany; and schema has now
protected $defaultSort = '-createdAt';

results are currently showing in ascending order, which is not right.

Let me know what info I need to provide further to quickly wrap this up.

My request doesn't have any sort query string.

image

Regards.

@lindyhopchris
Copy link
Contributor

Can you confirm you're on the latest version of the package?

So the $defaultSort property must be -created_at.

Can you confirm that it sorts by the correct order if you send the following request:

/api/v1/spaces?sort=-created_at

Can you also provide a copy & paste of the whole schema class?

@lindyhopchris
Copy link
Contributor

Can you also be clear about what you mean when you say "it is not working for me".

When you have $defaultSort property set, do you get an exception? Or does it just return the values unsorted?

@sahil-kindlebit
Copy link
Author

Hi, It returns values unsorted, I do not receive error.

My Schema file.

<?php

namespace App\JsonApi\V1\Spaces;

use App\Models\Space;
use LaravelJsonApi\Eloquent\Schema;
use LaravelJsonApi\Eloquent\Fields\ID;
use LaravelJsonApi\Eloquent\Fields\Str;
use LaravelJsonApi\Eloquent\Fields\Attribute;
use LaravelJsonApi\Eloquent\Fields\DateTime;
use LaravelJsonApi\Eloquent\Filters\WhereIdIn;
use LaravelJsonApi\Eloquent\Fields\SoftDelete;
use LaravelJsonApi\Eloquent\Contracts\Paginator;
use LaravelJsonApi\Eloquent\Fields\Relations\HasOne;
use LaravelJsonApi\Eloquent\Pagination\PagePagination;
use LaravelJsonApi\Eloquent\Fields\Relations\BelongsTo;

class SpaceSchema extends Schema
{
    protected $defaultSort = '-createdAt';
    /**
     * The model the schema corresponds to.
     *
     * @var string
     */
    public static string $model = Space::class;

    /**
     * Get the resource fields.
     *
     * @return array
     */
    public function fields(): array
    {
        return [
            ID::make(),
            Str::make('name'),
            Str::make('subdomain'),
            Str::make('logo'),
            Str::make('icon'),
            DateTime::make('created_at')->sortable()->readOnly(),
            DateTime::make('updated_at')->sortable()->readOnly(),
            BelongsTo::make('user_id')->type('users'),
            Str::make('password_current')->hidden(),
            SoftDelete::make('deleted_at'),
            HasOne::make('team_id')->type('teams'),
        ];
    }

    /**
     * Get the resource filters.
     *
     * @return array
     */
    public function filters(): array
    {
        return [
            WhereIdIn::make($this)
        ];
    }

    /**
     * Get the resource paginator.
     *
     * @return Paginator|null
     */
    public function pagination(): ?Paginator
    {
        return PagePagination::make();
    }
}

With
/api/v1/spaces?sort=-created_at
image

It works fine.

but with
/api/v1/spaces (with $defaultSort in schema)
it does not give desired results.

Attached is my package version info -
image

@lindyhopchris
Copy link
Contributor

lindyhopchris commented Jun 11, 2021

Your schema $defaultSort property should be -created_at.... the copy & paste shows it's -createdAt. Though there's something weird there as you should be getting an exception when using an invalid sort name.

Your image of the request with sort=-created_at does not show the resources in the correct order, i.e. that is not working either.

I strongly suspect you've got an old version of the package. Please run:

composer show laravel-json-api/laravel

And copy & paste the output here.

@lindyhopchris
Copy link
Contributor

Or try fixing it as follows:

composer require laravel-json-api/laravel:^1.0.0-beta.4 --no-update
composer up laravel-json-api/*

And then let me know whether it works or not.

@sahil-kindlebit
Copy link
Author

composer require laravel-json-api/laravel:^1.0.0-beta.4 --no-update
composer up laravel-json-api/*

this solved the issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants