Support the ongoing development of Laravel.io →
posted 11 years ago
Eloquent

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?

Last updated 3 years ago.
0

Use DB::raw(...).

In your case:

public static create($data) {
  $data['b'] = DB::raw('now()');
  parent::create($data);
}
Last updated 3 years ago.
0

why not use date("Y-m-d H:i:s") ?

Last updated 3 years ago.
0

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.

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

c0ntax c0ntax Joined 11 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.