I have a table with 3 columns:
firstname
lastname
fullname
in migration:
Schema::create('owners', function (Blueprint $table) {
$table->id();
$table->string('firstname',20);
$table->string('lastname', 20);
$table->string('fullname')->storedAs('CONCAT(firstname,lastname)');
$table->timestamps();
});
the problem is that i want to change the concatenation order in the controller i tried to use db statement but it doesn’t work
-in the controller:
$owners= Owner::findOrFail($id);
$owners->update([
'firstname'=>$request['firstname'],
'lastname' =>$request['lastname'],
]);
DB::statement('UPDATE owners SET fullname AS CONCAT(lastname,firstname) STORED WHERE ID=1 ');
I don’t want to just use a simple concatenation because the user can change the firstname or the lastname and the order that’s why I used storedAs()
any ideas please?
3
Answers
The
storedAs
method in the migration creates a generated column in mysql. The value is automatically generated from the column values of the firstname and the lastname. There’s no way you can change this via anUPDATE
statement. You’d have to use anALTER TABLE
statement, which would be horrifically bad practice.If I were you, I’d keep full name display as a model method so you could access it by using
$owner->fullNameFirstLast()
or$owner->fullNameLastFirst()
What you should do is create a new migration in order to change the column, the code would be something like this:
This way the column will be changed on a database level, and no need for the controller query you have added
Simply try this
1- update your migration to
2- in your controller
You can also write it this way
And the same way for your Create function as well