Laravel5 series tutorial 4: database and Eloquent

Source: Internet
Author: User
Laravel5 series tutorial 4: database and Eloquent

From: https://jellybool.com/post/programming-with-laravel-5-database-and-eloquent-model

In the previous article, I wrote some basic usage of Laravel Blade and several ways to pass variables to the view,

In this section, we will talk about the database configuration that deals with databases and Laravel's powerful Eloquent.

Laravel database configuration

This part prepares for the next section

Laravel's configuration files are under the config/folder in the project directory, which is under the blog/config folder. you can open this folder to see if you have many configuration files: such as mail. php (configured for the Mail sending service) and database. php (configure the database). here we will look at this database. php configuration file:

 'connections' => [        'mysql' => [            'driver'    => 'mysql',            'host'      => env('DB_HOST', 'localhost'),            'database'  => env('DB_DATABASE', 'forge'),            'username'  => env('DB_USERNAME', 'forge'),            'password'  => env('DB_PASSWORD', ''),            'charset'   => 'utf8',            'collation' => 'utf8_unicode_ci',            'prefix'    => '',            'strict'    => false,        ]        //...        ]

Open the file and you can see that it only returns a simple php array. Currently, we only care about the connections array. The above code does not provide all the database configurations. you can see that, because the blogger uses mysql, the mysql configuration will be provided here. you can refer to other databases, mysql will still be used in subsequent textbooks.

The configuration mentioned here is basically the configuration of the following four variables:

'Host' => env ('Db _ host', 'localhost'), // If. if the env file is not configured with DB_HOST, use localhost, which is the same as 'database' => env ('Db _ database', 'forge '), 'username' => env ('Db _ username', 'forge'), 'password' => env ('Db _ password ',''),

The env () method reads the configuration items in the. env (in blog/. env) file.

Open this file and you can see some common configurations, including the debug mode and development environment. you can also see the following operations:

DB_HOST=localhostDB_DATABASE=homesteadDB_USERNAME=homesteadDB_PASSWORD=secret

Because I use the development environment of Homestead, the above configuration is available (the default username and password of Homestead are homestead and secret ), if you directly use the php artisan serve method to enable service development, modify your configuration accordingly.

Why does Laravel adopt this configuration? One major reason may be the security and convenience of the file, so that when we need to push code to coding or Github, we can directly ignore this. the env file does not have to worry about leaking our core information. When deploying an application, you can directly create a. env file on the server, and write the corresponding configuration item.

In this way, as long as we configure the information correctly, we will connect to the database. of course, you must first create a homestead database.

Use Migration

After the database is connected, we need to create the corresponding data table. before Laravel is used, you may directly create the data table manually. for example, in this blog project, you will manually create an articles data table in the database, but in Laravel's project, I strongly recommend you use Migration. What are the advantages of this? In fact, you can regard Migration as a database version management tool, just like git's version management for our project files, you can rollback, you can reset, etc, it provides you with a combination of code implementation and command line to manage your database. if you execute php artisan in the command line under the blog/directory, you can see a lot of command lines, the following are the rollback and reset mentioned here:

The red box is usually used. if I haven't convinced me to use migration, let's go through this process again:

First, create a migration file, that is, define the schema of a table. run the following command line:

php artisan make:migration create_articles_table --create='articles'

After successful execution, we will get a migration file, which is located under database/migrations/. open this folder and you can see that Laravel already has two migration files, the users table and password-reset table are not used in this project. You can delete the file directly and open the migration File: create_articles_table.

 public function up()    {        Schema::create('articles', function (Blueprint $table) {            $table->increments('id');            $table->timestamps();        });    }    /**     * Reverse the migrations.     *     * @return void     */    public function down()    {        Schema::drop('articles');    }

There are two methods: up () and down (). The up () method is called When php artisan migrate is executed. This method creates an articles data table, while the down () method is executed when php artisan migrate: rollback is used, the article table will be deleted directly here.

However, do not rush to execute php artisan migrate here. we also need to add several fields for articles:

Public function up () {Schema: create ('articles', function (Blueprint $ table) {$ table-> increments ('id '); // primary key auto-increment $ table-> string ('title'); $ table-> text ('Intro'); $ table-> text ('content '); $ table-> timestamp ('hhed _ at'); $ table-> timestamps (); // Two automatically created fields: created_at and updated_at });}

Here, our intro field is the introduction of the article, and the published_at field is the posting date of the article. this is a great benefit for us to write a blog. you can control the posting date of the blog, because there are some articles I have written but not yet published, and I can use published_at to control the articles I don't want users to see. Then, let's execute php artisan migrate:

Then, the articles table is created successfully.

At this time, you may not have realized the benefits of migration. Imagine the following two scenarios:

1. during team development, how can we get the same database table design after team members put down our code pull? Do we need to export the table export and import it to every member? This is obviously unwise. if you use the migration command, you can get the same database table by running the 'php artisan migrate' command. 2. if a field in the articles table is wrong at this time, for example, if the intro field is incorrect, it should be named introduction. what should we do at this time? Directly manually change the database table? So back to the first scenario, do you need to manually change your team members? This is obviously not the way we like it. at this time, the advantage of migration is coming.

For example, here we will demonstrate how to solve the second scenario:

We only need to execute the following command line:

php artisan migrate:rollback

Then modify the intro field of the up () method:

$table->text('introduction');

Then execute php artisan migrate:

The big work is finished. for more features, see the document:

Http://laravel.com/docs/5.1/migrations

Use Eloquent

After we have created the articles table above, we can write a Model class for this table. you can create it manually or use the artisan command line to create a model, for example, if you type php artisan in the command line, you will see many commands under make, and make: model is the command we need:

Just as explained: Create a new Eloquent model class

In Laravel, we often have some naming conventions when creating a model:

If we have an articles data table, our model should be named Article; if we have an users data table, our model should be named User;

It is basically followed by the complex number of data tables, and the model singular can be capitalized.

Therefore, based on this rule, we will create our Article Model, using the make: model command:

php artisan make:model Article 

In this way, our Article Model is created successfully. This file is located in blog/app/Article. php. open it and we can see what Laravel has generated for us:

   

Note that the class Article inherits from our Eloquent \ Model class. Since this Eloquent \ Model class implements many great methods for us to use, we can have fun.

First of all, I started to play around by using the php artisan tinker tool to play around. tinker provides a command line interface for Eloquent to interact with database tables, you can write some simple php operations on it, such:

So let's instantiate an Article:

$article = new App\Article

This is equivalent to instantiating an Article class. we can perform field ing in subsequent operations.

When we create a table above, we have the following fields:

$table->increments('id');$table->string('title');$table->text('intro');$table->text('content');$table->timestamp('published_at');$table->timestamps();

Therefore, we can use tinker to set the following $ article fields, which is as simple as setting attributes.

For example, you can set the title of $ article as follows:

$article->title = 'Router Views Controllers';

Similarly, you can set the intro and content fields:

$article->intro = 'Article 1 Intro';$article->content = 'Article 1 Content';

However, it should be noted that the published_at field is used. here I recommend using a great time processing database Carbon, because the two fields, created_at and updated_at, also use the Carbon class, in this way, we will have a lot of benefits in subsequent processing. here we will use Carbon directly:

$article->published_at = Carbon\Carbon::now();

For $ table-> timestamps (), Laravel will automatically complete data insertion. Therefore, after each field is assigned, we can use the save () method of Eloquent to insert a piece of data to the articles table of the database:

$article->save();

When a value of true is returned, the data is successfully inserted. let's look at the database:

The above is a simple and complete process of using tinker to assign values to Eloquent.

Now let's have a bit of fun:

All () method

The all () method returns all records of the Article:

$articles = App\Article::all();

Find (), accepting a parameter $ id, such as searching for a record with id 1:

$article = App\Article::find(1);

You can also input an array of $ IDs to search for multiple records. However, here we only have one data record, so this is the case. But we can also play with it like this:

ToArray () method:

Convert an Eloquent object into an array:

$article = App\Article::find(1)->toArray();

ToJson () method

Convert an Eloquent object into a json string:

$article = App\Article::find(1)->toJson();

In this case, the Eloquent cannot be very powerful. Is there a where statement in the code writing process?

Don't worry, there will be:

Where () method
$article = App\Article::where('title','=','Router Views Controllers')->get();

When using where (), you often need to use get () to obtain the record set, which returns a Eloquent \ Collection result set, but if I want to record the first day that meets the conditions, what if I don't need a result set?

Use the first () method and replace get () with first ():

$article = App\Article::where('title','=','Router Views Controllers')->first();

Here, some simple searches can come to an end, but for update, we can do this:

$article = App\Article::find(1);$article->intro = 'Article 1 Intro Update!';$article->save();

Let's see if there are any updates:

$article = App\Article::find(1);

You can also use the update () method:

$article->update(['content'=>'Article 1 Content Update']);

Normally, we will get a MassAssignmentException with message:

See the document here: http://laravel.com/docs/5.1/eloquent#mass-assignment

This is because by default, Eloquent does not allow us to directly update our data. this is because data coverage may occur. However, if we do need to implement this function first, we can add a $ fillable array in the model file Article:

class Article extends Model{    protected $fillable = ['content'];}

Run the following command again:

Here, Ctrl + C is required to exit tinker and re-enter.

Search. after the update, when we talk about the concept of MassAssignment, we can talk about the create () method. this method can be used without declaring new Article () to create a data entry, for example:

 App\Article::create(['title'=>'Article 2','intro'=>'intro 2','content'=>'Article 2 content','published_at'=>Carbon\Carbon::now()]);

Then we will see a strange phenomenon. we didn't get the expected result:

We only have the content field with the correct value. title, intro, and published_at have no value. why? In fact, it is also because of MassAssignment. when referring to content, we can set the fields that can be filled in $ fillable in Article:

class Article extends Model{    protected $fillable = [        'title',        'intro',        'content',        'published_at'    ];}

Run the following command again:

After successfully creating a piece of data, we found that the second one was not what we wanted. let's delete it:

Use the delete () method:

$article = App\Article::find(2);$article->delete();

We use all () to check:

Destroy () can also be used here. this method can accept a $ id or an array $ ids:

App\Article::destroy(3);

Finally let's take a look at the official documentation: http://laravel.com/docs/5.1/eloquent

Next section

Here we will introduce the basic Eloquent. Since this section describes the Model, we have also touched Views and Controllers. The next section describes the basic process of Model Views Controllers.

Happy Hacking

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.