Greetings! I'm new to Laravel and frameworks in general and I have a question about where in my application to add scripts that would really only need to be used once.
As an example, this evening I wanted to split out a "first name" field between "first name" and "middle name" (since a big chunk of records in my database had middle name part of the first name, separated by a space. (Yes, I know there will be some exceptions here, but lets ignore that for now).
After doing the migration to add the middle name column, I was looking for the best way to update the data in my table. One approach would be just executing a MySQL query, but in this case I wanted to use eloquent and visualize the changes before modifying the records.
I really wasn't sure where to actually add the script to update the record. What I ended up doing was adding a route in routes.php
Route::get('/fix-names', 'StudentsController@update_name');
and a controller method
public function update_name()
{
Student::chunk(200, function ($students) {
foreach ($students as $student) {
$first_name = trim($student->first_name);
if (strpos($first_name, ' ') !== false) {
// okay! we have a space in the first name.
echo $first_name.' space detected! --- ';
$first_name_array = explode(' ', $first_name);
$real_first_name = $first_name_array[0];
echo 'so real first name is: '.$real_first_name;
$middle_name_array = array_shift($first_name_array);
$middle_name = implode(' ', $first_name_array);
echo '---- and the middle name is: '.$middle_name.'<br>';
$student->first_name = $real_first_name;
$student->middle_name = $middle_name;
$student->save();
}
}
});
}
When I finished the update (which worked just fine) I just commented out the route and method.
I can't help but feel gross about the way I handled this (by adding the route and the method to that controller and hitting that URL in my browser). I'm wondering if there's a better approach to these "one-off" types of scripts that may come up from time to time in my projects.
Any feedback would be appreciated!