skip to Main Content

I’m using Laravel 8. I would like to have a query, where all items from the users table are listed twice, one with created_at column, and second with updated_at column. The result of this array should be in an ascending date order (mix of created_at and updated_at dates).

My table:

enter image description here

Expected result:

Zoey  2022-10-19 ...
Peter 2022-10-20 ...
Zoey  2022-10-24 ...
Peter 2022-10-31 ...

How to do that in Laravel 8?

2

Answers


  1. First, create two queries:

    $result_one = DB::table('table')->select(['name','created_at AS field_date'])->get();
    $result_two = DB::table('table')->select(['name','updated_at AS field_date'])->get();
    

    Then merge the collections

    $results = $result_one->merge($result_two);
    

    And then you can sort them.

    $sorted_result = $results->sortBy('field_date');
    
    Login or Signup to reply.
  2. In order to accomplish this, you can use the union() method in Eloquent. Also, be sure to use selectRaw() so you can alias the date columns as date. The union will need the columns to have the same name:

    $usersCreatedAt = User::selectRaw('name, created_at AS date');
    $usersUpdatedAt = User::selectRaw('name, updated_at AS date');
    
    $users = $usersCreatedAt->union($usersUpdatedAt)->orderBy('date')->get();
    

    The result would be a collection like this:

    IlluminateDatabaseEloquentCollection {#5108
         all: [
           AppModelsUser {#5451
             name: "Zoey",
             date: "2022-10-19 18:46:50",
           },
           AppModelsUser {#5467
             name: "Peter",
             date: "2022-10-20 18:47:00",
           },
           AppModelsUser {#5443
             name: "Zoey",
             date: "2022-10-24 18:46:55",
           },
           AppModelsUser {#5459
             name: "Peter",
             date: "2022-10-31 18:47:06",
           },
         ],
       }
    

    Then you can get the array from it using ->toArray():

    return $users->toArray();
    

    Edit: Another good solution by @aynber. That solution uses Query Builder. So it depends on your code style on which you use 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search