Custom Casts to allow RAW Values #47395
-
I do have Point Geometry in my database table. It is currently not possible to have the point like 'Point(x,y)' as the attribute in the model and to save this to the database, because it handles the value as a string and does this on save: What I need is this or MySql just does not accept it: Currently I override the save() method to get a workaround:
Well this is a bit hacky in my opinion. Of course I could save a \DB::raw Object in attributes['location'], but this is quiet nasty when reading it out again. There is just no nice solution to this problem with current Custom Casts. First try was to have a mutator and a Cast at once, letting the Cast convert to /DB::raw . Took me an hour to figure out why the Cast was not called on save when there was a Mutator ( function getLocationAttribute() ) too. Therefore I request a Custom Cast Option to make the Cast result to be raw just on save. This is where it logically belongs to. If I save a number, the number will be value = 3 and not value = '3'. I need the same for my own attributes, even if PHP can only store them as text. If someone has a better cleaner idea, I am open to learn something. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
Does this not work?
<?php
namespace App\Casts;
use Illuminate\Support\Facades\DB;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class Point implements CastsAttributes
{
public function get($model, $key, $value, $attributes)
{
// https://stackoverflow.com/questions/37467050/convert-mysqls-point-to-text-in-php
return unpack('x4/corder/Ltype/dlng/dlat', $value);
}
public function set($model, $key, $value, $attributes)
{
return DB::raw(sprintf('POINT(%f, %f)', $value['lng'], $value['lat']));
}
} |
Beta Was this translation helpful? Give feedback.
-
Interesting. I will give it a try. Many thanks. |
Beta Was this translation helpful? Give feedback.
Does this not work?
App\Casts\Point.php