Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 1. Creating Records: using ::create with Model
- method 1:
- // create a bear
- Bear::create(array(
- 'name' => 'Super Cool',
- 'type' => 'Black',
- 'danger_level' => 1
- ));
- method 2:
- // alternatively you can create an object, assign values, then save
- $bear = new Bear;
- $bear->name = 'Super Cool';
- $bear->type = 'Black';
- $bear->danger_level = 1;
- // save the bear to the database
- $bear->save();
- method 3:
- // find the bear or create it into the database
- Bear::firstOrCreate(array('name' => 'Lawly'));
- 2. Getting and Finding Records
- // get all the bears
- $bears = Bear::all();
- // find a specific bear by id
- $bear = Bear::find(1);
- // find a bear by a specific attribute
- $bearLawly = Bear::where('name', '=', 'Lawly')->first();
- // find a bear with danger level greater than 5
- $dangerousBears = Bear::where('danger_level', '>', 5)->get();
- // First vs Get
- // When querying the database and creating where statements, you will have to use get() or first().
- // first will return only one record and
- // get will return an array of records that you will have to loop over.
- 3. Updating Records
- // find the bear
- $lawly = Bear::where('name', '=', 'Lawly')->first();
- // change the attribute
- $lawly->danger_level = 10;
- // save to our database
- $lawly->save();
- 4. Deleting Records
- // find and delete a record
- $bear = Bear::find(1);
- $bear->delete();
- // delete a record
- Bear::destroy(1);
- // delete multiple records
- Bear::destroy(1, 2, 3);
- // find and delete all bears with a danger level over 5
- Bear::where('danger_level', '>', 5)->delete();
Add Comment
Please, Sign In to add comment