1// If there's a flight from Oakland to San Diego, set the price to $99.
2// If no matching model exists, create one.
3$flight = App\Flight::updateOrCreate(
4 ['departure' => 'Oakland', 'destination' => 'San Diego'],
5 ['price' => 99, 'discounted' => 1]
6);
1$user = User::updateOrCreate(
2 ['email' => request('email')],
3 ['name' => request('name')]
4);
5
6// Do other things with the User
7
8
1// Retrieve flight by name, or create it if it doesn't exist...
2$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);
3
4// Retrieve flight by name, or create it with the name, delayed, and arrival_time attributes...
5$flight = App\Flight::firstOrCreate(
6 ['name' => 'Flight 10'],
7 ['delayed' => 1, 'arrival_time' => '11:30']
8);
9
10// Retrieve by name, or instantiate...
11$flight = App\Flight::firstOrNew(['name' => 'Flight 10']);
12
13// Retrieve by name, or instantiate with the name, delayed, and arrival_time attributes...
14$flight = App\Flight::firstOrNew(
15 ['name' => 'Flight 10'],
16 ['delayed' => 1, 'arrival_time' => '11:30']
17);
1// If there's a flight from Oakland to San Diego, set the price to $99.
2// If no matching model exists, create one.
3$flight = App\Models\Flight::updateOrCreate(
4 ['departure' => 'Oakland', 'destination' => 'San Diego'],
5 ['price' => 99, 'discounted' => 1]
6);
1firstOrCreate() will automatically create a new entry in the database if there is not match found. Otherwise it will give you the matched item.
2firstOrNew() will give you a new model instance to work with if not match was found, but will only be saved to the database when you explicitly do so (calling save() on the model). Otherwise it will give you the matched item.
1$userData = array('username' => 'Me', 'email' => 'me@yahoo.com');
2User::create($userData);
3