The introduction

After storing a lot of knowledge about routing and controller in the previous chapters, we started to interact with the database and get rid of the complicated and difficult to maintain SQL operations. Laravel provides the M model function of MVC.

This week we’ll start by looking at how to insert new items, or update existing items, into the model.

Code time

When we built a Hello World page, we showed you how to use Laravel’s command-line scaffolding to create new model files and create database tables through migration. This links up the data operations.

In general, a new piece of data can be created in an object-oriented fashion by writing:

$event = new Event;
$event->name = 'Coffee and Laravel';
$event->venue = 'The Mocha Factory';
$event->save();
Copy the code

Notice that after the object is created, we directly manipulate the object properties, assign values to them, and then call the save method to complete the creation of the data.

We also have id fields in the table, creATED_AT fields, and updated_AT fields, which are not explicitly assigned. But when you open the database table to see the results, those values have also been written successfully.

Original as follows:

  • The id field is an auto_increment constraint.
  • The created_AT/updated_AT field uses $TIMESTAMP = true in the Event model. Laravel then updates the two fields by default when processing model data.

However, not all fields are allowed to be written to the data that is written to the database. Within the model we can manually specify which fields can and cannot be written. Just add the following:

protected $fillable = ['name'.'venue'];
Copy the code

This allows the specified two field values to be written and the rest to be discarded.

For example, the User model, which controls the User permission resources, is very important. If you have a field is_admin that specifies whether or not you are a “super administrator,” it can cause a lot of trouble if you accidentally write to it using an array or otherwise.

We can “protect” it within the model:

class User extends Model
{
	protected $guarded = ['is_admin'];
}
Copy the code

This eliminates writing of this field when using the User model to write to the database.

Create or update

Then we introduce some syntactic sugar of laravel model. A common scenario, such as when writing data, determines whether the record exists in the database table, creates it if it does not, and returns it if it does.

The model has a syntactic sugar method firstOrCreate, to give an example:

$event = Event::firstOrCreate(['name'= >'Coffee and Laravel']);
Copy the code

The above code is equivalent to the following:

$event = Event::where('name'.'Coffee and Laravel')->first();
if (is_null($event)) {
    $event = Event::create(['name'= >'Coffee and Laravel']);
}
Copy the code

An Event object is always returned, so if you want to move on to other properties, just do it:

$event->venue = 'Starclucks';
$event->save();
Copy the code

This is the second SQL operation, which takes effect immediately.

The firstOrCreate method also receives a second parameter to specify when creating data entries if the first parameter query statement is not standing. The code is as follows:

$event = Event::firstOrCreate(['name'= >'Coffee and Laravel'], ['venue'= >'Starclucks'.'city'= >'Dublin']);
Copy the code

If the name field already exists, the first data is returned; If not, write to the second array.

Laravel also has a firstOrNew method for not writing to the database immediately until manually:

$event = Event::firstOrNew(['name'= >'Coffee and Laravel']);
$event->venue = 'Starclucks';
$event->save();
Copy the code

Write in the last

This article showed you how to protect fields by manually specifying the allowed fields through a simple data manipulation. And details of the use of two grammatical sugars.

Happy coding 🙂

I am a @programmer assistant, an original author in the IT field who focuses on programming knowledge and circle dynamics

🏆 nuggets technical essay | double festival special articles