Hi there. I'm new to Laravel so please be gentle with me! I'm a little stumped as to how I would go about inserting a function rather than a value using Eloquent. For example
INSERT INTO test (a, b) VALUES ('hello', NOW());
UPDATE test set b = NOW() WHERE a = 'hello';
If I wanted this to happen automagically would it be best to overload the create and save methods such as:
public static create($data) {
$data['b'] = 'NOW()';
parent::create($data);
}
As it stands, that's going to try to insert the string 'NOW()' into the database and not run the NOW() function. What's the trick?
Use DB::raw(...)
.
In your case:
public static create($data) {
$data['b'] = DB::raw('now()');
parent::create($data);
}
Worked a treat!
The reason I didn't use date("Y-m-d H:i:s") was that I wasn't really all that interested in NOW() as the actual function. I'm doing some work with PostGIS which requires a whole load of stuff like:
$this->geom_point = DB::raw('ST_SetSRID(ST_MakePoint(' . $this->longitude . ',' . $this->latitude . '), ' . $this->srid . ')');
So I was looking for the more generic solution.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community