Laravel eloquent model creation, update and batch assignment detailed explanation

Source: Internet
Author: User


1. Create the Model

1.1 Creating a model using the Save method

Call the Save method of the eloquent model class to create the model and insert the data into the database:

$post = new Post;
$post->title = ' Test 4 ';
$post->content = ' test content ';
$post->user_id = 1;
$post->cat_id = 1;
if ($post->save ()) {
Echo ' Add article success! ';
}else{
Echo ' Add article failed! ';
}

Access Http://laravel.app:8000/test in the browser if the output is:

Add article Success!
It indicates that the insert was successful and we went to the database to view the data, and we did add a record:


1.2 Inserting data using the Create method

In addition, you can use the Create method to insert data, because the method uses a bulk assignment (Mass assignment), so we need to set the $fillable property or $guarded property in the model class to indicate which properties can be set by this method. which cannot be.

Before we start, let's explain what a batch assignment is and why you should use a bulk assignment.

The English name of the batch assignment is mass assignment, and the so-called bulk assignment is when we send an array to the model class to create the new model instance (usually the form request data), we can do it in the following way simply:

$post = Post::create (Input::all ());

Instead of setting property values as one with the Save method, if the model has a lot of properties, using Save is a nightmare with wood.

But things are always relative, using bulk assignment is convenient, but it also poses a security risk, and many times the model class has some property values that are not what we expect to be modified by batch assignment, such as the user model has a User_type attribute, and if the user modifies its type to an administrator type by requesting data, This is clearly not allowed, and it is based on this consideration that the eloquent model class provides us with the $fillable and $guarded attributes, which we can view as "whitelist" and "blacklist", and attributes defined in $fillable can be assigned by a batch assignment. Attributes that are defined in $guarded are filtered out in bulk assignment.

So what if we really want to modify the attributes defined in $guarded? The answer is to use the Save method.

Also note that the $fillable and $guarded methods can only be defined at the same time, the reason is very simple, not black or white, define a different one is OK.

The visible batch assignment not only provides convenience for us to create the model, but also avoids the hidden danger and improves the security of the system.

Let's show you how to use the batch assignment. First, define the $guarded properties in the post model as follows:

protected $guarded = [' views ', ' user_id ', ' updated_at ', ' created_at '];

Then implement the logic for creating the model instance in the controller:

$input = [
' title ' => ' Test 5 ',
' Content ' => ' test content ',
' cat_id ' =>1,
' Views ' =>100,
' user_id ' =>2
];
$post = Post::create ($input);
DD ($post);

Enter Http://laravel.app:8000/test in the browser, the page output:

The visible user_id and views fields are not inserted, which is exactly what $guarded is doing, and it is simple to set both values:

$input = [
' title ' => ' Test 5 ',
' Content ' => ' test content ',
' cat_id ' =>1,
' Views ' =>100,
' user_id ' =>2
];
$post = Post::create ($input);
$post->user_id = 2;
$post->views = 100;
$post->save ();
DD ($post);

The corresponding output is as follows:

1.3 Other methods of inserting data

The eloquent model class also supports other methods of inserting data--firstorcreate and firstornew, both by looking up matching records in the database by passing in property values, and creating a new model instance if not found. The difference is that the latter does not persist data to the database, and requires that the Save method be invoked.

2, update the model

2.1 Updating the model with the Save method

The Save method can also be used to update the model, to update the model data, to get the model instance, to modify the model properties, and then to save by calling the Save method:

$post = Post::find (1);
$post->title = ' Test 1 title ';
if ($post->save ()) {
Echo ' updates the article successfully! ';
}else{
Echo ' Update article failed! ';
}

Access Http://laravel.app:8000/test in the browser, if displayed:

Update article Success!

Indicates that the database corresponding table record has been updated successfully:

2.2 Updating data using the Update method

Corresponding to create, the eloquent model class also supports updating data using the Update method, which also uses bulk assignments:

$input = [
' title ' => ' Test 6 title ',
' Content ' => ' test Content 6 ',
' cat_id ' =>1,
' Views ' =>200,
' user_id ' =>1
];
$post = Post::find (6);
if ($post->update ($input)) {
Echo ' updates the article successfully! ';
DD ($post);
}else{
Echo ' Update article failed! ';
}

The corresponding output is:

Visible user_id and views are not updated.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.