I'm very new to Laravel and php frameworks in general, so sorry if I miss anything basic. I've created a new model called Journey
in my application which extends the standard Eloquent
model. What I've noticed is that I'm using my Journey model in two different Controllers and I'm duplicating a bit of code because of it.
Essentially, what I'm doing is I'm taking the title of a Journey and I'm formatting it with a custom class to clean the title (convert to lowercase, add hyphens, remove whitespace, etc) so I can append it to my page URLs.
In one controller, I'm calling:
$journey = Journey::find($id);
$journey->cleanURL = Url::clean($journey['name']); // This creates a new element/property with a clean string
And in the other, I'm calling:
$journeys = Journey::all();
foreach ($journeys as $journey) {
$journey->cleanURL = URL::clean($journey['name']);
}
It would be inappropriate to add a fixed field to my database with the cleaned URL because I may change the title (which the cleaned URL is based on) at any time and I'd like the URL to update automatically in this event. However, saying this, I'm repeating myself by calling Url::clean
twice.
What I'd like to do is write a method or alter an existing method, so that when I call Journey::all()
or Journey::find()
or any query-based method, the URL field is already present and filled. I've tried looking through some of the Vendor/Eloquent
files, but they just make me confused.
How would I go about doing this?