Home > Back-end >  How to create a custom collection function to modify model data?
How to create a custom collection function to modify model data?

Time:10-09

I have a model called Presence that stores user's presences as recurring events, where each row has a start and end date, a frequency, and an interval. In that way, I can use RRule to create events from a single database row.

Now when I fetch the data like Presence::all() I want to add a ->toRrule() (like the ->toArray()) so that the final data is modified to be a list of single events.

E.g.:

 ---- ------------ ------------ ---------- ----------- 
| id |   start    |    end     | interval | frequency |
 ---- ------------ ------------ ---------- ----------- 
|  1 | 2022-10-01 | 2022-10-03 |        1 | DAILY     |
 ---- ------------ ------------ ---------- ----------- 

I would get this row with Presence::first() and I want to get the following with Presence::all()->toRrule():

[
   [
      'start' => '2022-10-01'
      'end' => '2022-10-01'
   ],
   [
      'start' => '2022-10-02'
      'end' => '2022-10-02'
   ],
   [
      'start' => '2022-10-03'
      'end' => '2022-10-03'
   ],
]

Regardless of what the actual function does, a) is this an elegant way? and b) how and especially where do I create this function?

CodePudding user response:

Without going into the path of optimizing the design of your solution. Laravel offers a way to have custom collection for your Presence model, and there you can define your toRule() function. And it will be exactly in the way you are searching for. Find the official doc here https://laravel.com/docs/9.x/eloquent-collections#custom-collections

Good luck.

CodePudding user response:

I really cannot tell if it is an elegant way since you did not specify what the function does.

You should add this function in your Model file. Now for the Presence model, you should head to the file app/models/Presence.php then add the function this way:

public static function toRrule() {
...
}

Now if you want to access the function on the Presence model, you simply do it this way Presence::all()->toRrule()

  • Related