How to use orderBy() with model's method in Laravel












-2















How can I use orderBy to order by a model's method?



Consider the model User and the method



public function fullName() {
return $this->firstName . $this->lastName;
}


I want to do something like orderBy('fullName'). Is this possible? I know I can make equivalent code using Query Builder, but I want to keep my Model methods as they are.










share|improve this question

























  • short answer, no, thats not possible. orderBy() will be translated into SQL Order BY which it have no idea about your fullname().. as last resort, you may consider using DB::raw() to concat things.

    – Bagus Tesa
    Nov 23 '18 at 0:50













  • so I'll have to use DB:raw() to rewrite all of my methods

    – Josh
    Nov 23 '18 at 0:52











  • sadly yes, or you may use denormalization trick instead. create a column named fullname and have it assigned every model saving.. oh wait they had orderByRaw on 5.7 - probably can do something like ->orderByRaw('CONCAT(firstname, lastname)'), may i know what version of your Laravel?

    – Bagus Tesa
    Nov 23 '18 at 0:55











  • I'm using 5.7. I would like to keep my existing methods, but it seems I'll have to code them using DB:raw().

    – Josh
    Nov 23 '18 at 0:57











  • no, you still have that orderByRaw :(

    – Bagus Tesa
    Nov 23 '18 at 1:14
















-2















How can I use orderBy to order by a model's method?



Consider the model User and the method



public function fullName() {
return $this->firstName . $this->lastName;
}


I want to do something like orderBy('fullName'). Is this possible? I know I can make equivalent code using Query Builder, but I want to keep my Model methods as they are.










share|improve this question

























  • short answer, no, thats not possible. orderBy() will be translated into SQL Order BY which it have no idea about your fullname().. as last resort, you may consider using DB::raw() to concat things.

    – Bagus Tesa
    Nov 23 '18 at 0:50













  • so I'll have to use DB:raw() to rewrite all of my methods

    – Josh
    Nov 23 '18 at 0:52











  • sadly yes, or you may use denormalization trick instead. create a column named fullname and have it assigned every model saving.. oh wait they had orderByRaw on 5.7 - probably can do something like ->orderByRaw('CONCAT(firstname, lastname)'), may i know what version of your Laravel?

    – Bagus Tesa
    Nov 23 '18 at 0:55











  • I'm using 5.7. I would like to keep my existing methods, but it seems I'll have to code them using DB:raw().

    – Josh
    Nov 23 '18 at 0:57











  • no, you still have that orderByRaw :(

    – Bagus Tesa
    Nov 23 '18 at 1:14














-2












-2








-2








How can I use orderBy to order by a model's method?



Consider the model User and the method



public function fullName() {
return $this->firstName . $this->lastName;
}


I want to do something like orderBy('fullName'). Is this possible? I know I can make equivalent code using Query Builder, but I want to keep my Model methods as they are.










share|improve this question
















How can I use orderBy to order by a model's method?



Consider the model User and the method



public function fullName() {
return $this->firstName . $this->lastName;
}


I want to do something like orderBy('fullName'). Is this possible? I know I can make equivalent code using Query Builder, but I want to keep my Model methods as they are.







laravel laravel-5 eloquent laravel-query-builder






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 24 '18 at 19:05







Josh

















asked Nov 23 '18 at 0:48









JoshJosh

268




268













  • short answer, no, thats not possible. orderBy() will be translated into SQL Order BY which it have no idea about your fullname().. as last resort, you may consider using DB::raw() to concat things.

    – Bagus Tesa
    Nov 23 '18 at 0:50













  • so I'll have to use DB:raw() to rewrite all of my methods

    – Josh
    Nov 23 '18 at 0:52











  • sadly yes, or you may use denormalization trick instead. create a column named fullname and have it assigned every model saving.. oh wait they had orderByRaw on 5.7 - probably can do something like ->orderByRaw('CONCAT(firstname, lastname)'), may i know what version of your Laravel?

    – Bagus Tesa
    Nov 23 '18 at 0:55











  • I'm using 5.7. I would like to keep my existing methods, but it seems I'll have to code them using DB:raw().

    – Josh
    Nov 23 '18 at 0:57











  • no, you still have that orderByRaw :(

    – Bagus Tesa
    Nov 23 '18 at 1:14



















  • short answer, no, thats not possible. orderBy() will be translated into SQL Order BY which it have no idea about your fullname().. as last resort, you may consider using DB::raw() to concat things.

    – Bagus Tesa
    Nov 23 '18 at 0:50













  • so I'll have to use DB:raw() to rewrite all of my methods

    – Josh
    Nov 23 '18 at 0:52











  • sadly yes, or you may use denormalization trick instead. create a column named fullname and have it assigned every model saving.. oh wait they had orderByRaw on 5.7 - probably can do something like ->orderByRaw('CONCAT(firstname, lastname)'), may i know what version of your Laravel?

    – Bagus Tesa
    Nov 23 '18 at 0:55











  • I'm using 5.7. I would like to keep my existing methods, but it seems I'll have to code them using DB:raw().

    – Josh
    Nov 23 '18 at 0:57











  • no, you still have that orderByRaw :(

    – Bagus Tesa
    Nov 23 '18 at 1:14

















short answer, no, thats not possible. orderBy() will be translated into SQL Order BY which it have no idea about your fullname().. as last resort, you may consider using DB::raw() to concat things.

– Bagus Tesa
Nov 23 '18 at 0:50







short answer, no, thats not possible. orderBy() will be translated into SQL Order BY which it have no idea about your fullname().. as last resort, you may consider using DB::raw() to concat things.

– Bagus Tesa
Nov 23 '18 at 0:50















so I'll have to use DB:raw() to rewrite all of my methods

– Josh
Nov 23 '18 at 0:52





so I'll have to use DB:raw() to rewrite all of my methods

– Josh
Nov 23 '18 at 0:52













sadly yes, or you may use denormalization trick instead. create a column named fullname and have it assigned every model saving.. oh wait they had orderByRaw on 5.7 - probably can do something like ->orderByRaw('CONCAT(firstname, lastname)'), may i know what version of your Laravel?

– Bagus Tesa
Nov 23 '18 at 0:55





sadly yes, or you may use denormalization trick instead. create a column named fullname and have it assigned every model saving.. oh wait they had orderByRaw on 5.7 - probably can do something like ->orderByRaw('CONCAT(firstname, lastname)'), may i know what version of your Laravel?

– Bagus Tesa
Nov 23 '18 at 0:55













I'm using 5.7. I would like to keep my existing methods, but it seems I'll have to code them using DB:raw().

– Josh
Nov 23 '18 at 0:57





I'm using 5.7. I would like to keep my existing methods, but it seems I'll have to code them using DB:raw().

– Josh
Nov 23 '18 at 0:57













no, you still have that orderByRaw :(

– Bagus Tesa
Nov 23 '18 at 1:14





no, you still have that orderByRaw :(

– Bagus Tesa
Nov 23 '18 at 1:14












2 Answers
2






active

oldest

votes


















0














I think you have a few options here:




  1. Create a view in your database, which has the column fullName. Then change your model to use the view.

  2. Create a computed column fullName so that on insert if will use the values given from firstName and lastName.

  3. Use Laravel's Collection class. This class provides a sortBy method which you can use an attributes.


If you go with option 2, first define an attribute:



public function getFullNameAttribute()
{
return $this->firstName . $this->lastName;
}


Then using Laravel's Collection:



$items = Model::all()->sortBy('FullName');


Note: The default option for sortBy is ascending, so if you wish to sort descending:



$items = Model::all()->sortByDesc('FullName');


You can read more about accessors here: https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor






share|improve this answer
























  • I can't use sortBy, because I'm using pagination and Collections don't have pagination.

    – Josh
    Nov 23 '18 at 12:11



















0














I've solved the problem with this solution:



$sorted = User::get()
->sortBy('full_name') //appended attribute
->pluck('id')
->toArray();

$orderedIds = implode(',', $sorted);

$result = DB::table('user')
->orderByRaw(DB::raw("FIELD(id, ".$orderedIds." )"))
->paginate(10);


I've appended fullName attribute to the model, to be used by sortBy.
With this solution I was able to use orderBy to order by an appended attribute of the model, exactly what I wanted to do. So yes, it is possible. And also I was able to use pagination. Thanks to all who tried to help.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53439483%2fhow-to-use-orderby-with-models-method-in-laravel%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I think you have a few options here:




    1. Create a view in your database, which has the column fullName. Then change your model to use the view.

    2. Create a computed column fullName so that on insert if will use the values given from firstName and lastName.

    3. Use Laravel's Collection class. This class provides a sortBy method which you can use an attributes.


    If you go with option 2, first define an attribute:



    public function getFullNameAttribute()
    {
    return $this->firstName . $this->lastName;
    }


    Then using Laravel's Collection:



    $items = Model::all()->sortBy('FullName');


    Note: The default option for sortBy is ascending, so if you wish to sort descending:



    $items = Model::all()->sortByDesc('FullName');


    You can read more about accessors here: https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor






    share|improve this answer
























    • I can't use sortBy, because I'm using pagination and Collections don't have pagination.

      – Josh
      Nov 23 '18 at 12:11
















    0














    I think you have a few options here:




    1. Create a view in your database, which has the column fullName. Then change your model to use the view.

    2. Create a computed column fullName so that on insert if will use the values given from firstName and lastName.

    3. Use Laravel's Collection class. This class provides a sortBy method which you can use an attributes.


    If you go with option 2, first define an attribute:



    public function getFullNameAttribute()
    {
    return $this->firstName . $this->lastName;
    }


    Then using Laravel's Collection:



    $items = Model::all()->sortBy('FullName');


    Note: The default option for sortBy is ascending, so if you wish to sort descending:



    $items = Model::all()->sortByDesc('FullName');


    You can read more about accessors here: https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor






    share|improve this answer
























    • I can't use sortBy, because I'm using pagination and Collections don't have pagination.

      – Josh
      Nov 23 '18 at 12:11














    0












    0








    0







    I think you have a few options here:




    1. Create a view in your database, which has the column fullName. Then change your model to use the view.

    2. Create a computed column fullName so that on insert if will use the values given from firstName and lastName.

    3. Use Laravel's Collection class. This class provides a sortBy method which you can use an attributes.


    If you go with option 2, first define an attribute:



    public function getFullNameAttribute()
    {
    return $this->firstName . $this->lastName;
    }


    Then using Laravel's Collection:



    $items = Model::all()->sortBy('FullName');


    Note: The default option for sortBy is ascending, so if you wish to sort descending:



    $items = Model::all()->sortByDesc('FullName');


    You can read more about accessors here: https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor






    share|improve this answer













    I think you have a few options here:




    1. Create a view in your database, which has the column fullName. Then change your model to use the view.

    2. Create a computed column fullName so that on insert if will use the values given from firstName and lastName.

    3. Use Laravel's Collection class. This class provides a sortBy method which you can use an attributes.


    If you go with option 2, first define an attribute:



    public function getFullNameAttribute()
    {
    return $this->firstName . $this->lastName;
    }


    Then using Laravel's Collection:



    $items = Model::all()->sortBy('FullName');


    Note: The default option for sortBy is ascending, so if you wish to sort descending:



    $items = Model::all()->sortByDesc('FullName');


    You can read more about accessors here: https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 23 '18 at 4:59









    adamadam

    949811




    949811













    • I can't use sortBy, because I'm using pagination and Collections don't have pagination.

      – Josh
      Nov 23 '18 at 12:11



















    • I can't use sortBy, because I'm using pagination and Collections don't have pagination.

      – Josh
      Nov 23 '18 at 12:11

















    I can't use sortBy, because I'm using pagination and Collections don't have pagination.

    – Josh
    Nov 23 '18 at 12:11





    I can't use sortBy, because I'm using pagination and Collections don't have pagination.

    – Josh
    Nov 23 '18 at 12:11













    0














    I've solved the problem with this solution:



    $sorted = User::get()
    ->sortBy('full_name') //appended attribute
    ->pluck('id')
    ->toArray();

    $orderedIds = implode(',', $sorted);

    $result = DB::table('user')
    ->orderByRaw(DB::raw("FIELD(id, ".$orderedIds." )"))
    ->paginate(10);


    I've appended fullName attribute to the model, to be used by sortBy.
    With this solution I was able to use orderBy to order by an appended attribute of the model, exactly what I wanted to do. So yes, it is possible. And also I was able to use pagination. Thanks to all who tried to help.






    share|improve this answer




























      0














      I've solved the problem with this solution:



      $sorted = User::get()
      ->sortBy('full_name') //appended attribute
      ->pluck('id')
      ->toArray();

      $orderedIds = implode(',', $sorted);

      $result = DB::table('user')
      ->orderByRaw(DB::raw("FIELD(id, ".$orderedIds." )"))
      ->paginate(10);


      I've appended fullName attribute to the model, to be used by sortBy.
      With this solution I was able to use orderBy to order by an appended attribute of the model, exactly what I wanted to do. So yes, it is possible. And also I was able to use pagination. Thanks to all who tried to help.






      share|improve this answer


























        0












        0








        0







        I've solved the problem with this solution:



        $sorted = User::get()
        ->sortBy('full_name') //appended attribute
        ->pluck('id')
        ->toArray();

        $orderedIds = implode(',', $sorted);

        $result = DB::table('user')
        ->orderByRaw(DB::raw("FIELD(id, ".$orderedIds." )"))
        ->paginate(10);


        I've appended fullName attribute to the model, to be used by sortBy.
        With this solution I was able to use orderBy to order by an appended attribute of the model, exactly what I wanted to do. So yes, it is possible. And also I was able to use pagination. Thanks to all who tried to help.






        share|improve this answer













        I've solved the problem with this solution:



        $sorted = User::get()
        ->sortBy('full_name') //appended attribute
        ->pluck('id')
        ->toArray();

        $orderedIds = implode(',', $sorted);

        $result = DB::table('user')
        ->orderByRaw(DB::raw("FIELD(id, ".$orderedIds." )"))
        ->paginate(10);


        I've appended fullName attribute to the model, to be used by sortBy.
        With this solution I was able to use orderBy to order by an appended attribute of the model, exactly what I wanted to do. So yes, it is possible. And also I was able to use pagination. Thanks to all who tried to help.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 24 '18 at 19:05









        JoshJosh

        268




        268






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53439483%2fhow-to-use-orderby-with-models-method-in-laravel%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Post-Redirect-Get with Spring WebFlux and Thymeleaf

            Xamarin.form Move up view when keyboard appear

            JBPM : POST request for execute process go wrong