There are a few helpful Eloquent functions that help you to know whether the Eloquent object was changed recently or during the request of Laravel.
Example 1: wasRecentlyCreated()
So there is firstOrCreate()
, which tries to find the first record by email or creates that with name and password.
use App\Models\User; class HomeController extends Controller{ public function index() { $user = User::firstOrCreate( ['name' => 'Admin', 'password' => bcrypt('password')] ); dump($user->wasRecentlyCreated ? 'Created' : 'Found'); }}
And there's wasRecentlyCreated
. This is a property, not a function.
And if you launch that code on an empty database the first time, it will say created because it created the object, but if you relaunch it the second time, it will say found because it didn't create the object during that second request.
Example 2: isDirty()
The second helpful method is isDirty()
. If you change any Eloquent method property during...