Laravel 5 Series Tutorial four: Databases and eloquent

Source: Internet
Author: User
Tags tojson

Free Video Tutorial Address Https://laravist.com/series/laravel-5-basic

The previous article wrote some basic usages of laravel blade and several ways to pass variables to the view,

In this section, we talk about database configurations and laravel powerful eloquent that deal with databases.

Database configuration for Laravel

This section prepares you for the next section.

Laravel configuration files are in the project directory under the config/ folder, here is the folder blog/config , you can open this folder to see that you have a lot of configuration files: mail.php(配置邮件发送服务的) and database.php(配置数据库的) , we are here to see this database.php configuration file:

 ' Connections ' = [' MySQL ' = [' Driver ' =' MySQL ', ' host ' = env ( ' Db_host ',  ' database ' = env ( ' db_database ',  ' Forge '),  ' username ' = env ( ' Db_username ', Span class= "hljs-string" > ' Forge '),  ' password ' = env ( db_ PASSWORD ',  ' charset ' =  UTF8 ',  ' collation ' =  ' utf8_unicode_ci ',  prefix ' = ",  ' strict ' = false," //...]          

To open the file, you can see that the inside just returns a simple PHP array just as we currently care about connections this array. The above code does not give all the database configuration, you can see for yourself, because bloggers are using MySQL, so here will give the configuration of MySQL, other databases you can refer to, the subsequent textbook blogger will still use MySQL.

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

‘host‘      => env(‘DB_HOST‘, ‘localhost‘),//如果.env文件没有DB_HOST配置,则取localhost,后面的一样‘database‘ => env(‘DB_DATABASE‘, ‘forge‘),‘username‘ => env(‘DB_USERNAME‘, ‘forge‘),‘password‘ => env(‘DB_PASSWORD‘, ‘‘),

The env () method here is to read the (位于blog/.env) config entry in the. env file.

Open this file, you can see some common configuration, including debug mode and development environment, you can also see the following several of us need to operate the options:

DB_HOST=localhostDB_DATABASE=homesteadDB_USERNAME=homesteadDB_PASSWORD=secret

Since I am using the Homestead development environment here, I have the above configuration (Homestead的默认用户名和密码为homestead和secret) , if you are directly using php artisan serve this way to open the service to develop, then modify your configuration accordingly.

Why should laravel take such a configuration? A big reason might be to consider the security and convenience of the file, so that when we need to push the code to coding or github, we can ignore the .env file directly without worrying about the disclosure of our core information. When deploying the application, we can create a file directly on the server .env , and write the corresponding configuration item on the OK.

So, as soon as we properly configure the information, we connect to the database, of course, you have to create a homestead database first.

Using migration

After the database is connected, we need to create the corresponding data table, you may have to manually create the data table before using Laravel, such as our blog project, you will go to the database manually create a articles data table, but in the Laravel project, I highly recommend you to use migration, so what is the benefit? In fact, you can think of migration as a database version management tool, just like git for our project file version management, you can rollback , you can, and reset it gives you a code implementation and command line combination way to manage your database, if you are in the blog/ directory, Command line execution php artisan , you can see a lot of command line, here are some of what we are talking about here rollback and reset so on:

Red box These basic is more commonly used, if I have not persuaded to use migration here, then we will go through this process:

First, we create a migration file that defines a table schema , and the command line executes:

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

After the smooth execution, we will get a migration file, which is located under database/migrations/, open this folder, you can see laravel there are two migration files, The Users table and the password-reset table, we do not currently have these two files in this project. So you can simply delete and open the migration file we just generated: create_articles_table This file

  public  function up () {schema::create (function  (Blueprint Span class= "hljs-variable" > $table) { $table->increments ( ' id ');  $table->timestamps ();}); } /** * Reverse the migrations. * * @return void */public function down< Span class= "Hljs-params" () {Schema::d rop (      

Here are two ways: up() and down() . The method up() is php artisan migrate called at execution time, this method creates a articles data table, and the down() method is executed in php artisan migrate:rollback the use, and articles this data table is deleted directly.

However, there is no rush to execute here php artisan migrate , we also need to add several fields for articles:

Publicfunctionup () {schema::create ( ' articles ', Span class= "hljs-function" >function  (Blueprint  $table) { $table->increments ( ' id '); //primary key auto-increment  $table->string ( $table->text ( ' intro ');  $table->text ( ' content ');  $table->timestamp ( ' published_at ');  $table->timestamps (); //automatically created two fields: Created_at and Updated_at}); } 

Here our intro field is an introduction to the article, the published_at field is the publication date of the article, so that it is very good for us to write a blog, you can control the publication date of the blog, because there are some I have written but have not yet published the date, I do not want to let users see the article I can use published_at To control it. After that, let's take a look at the following php artisan migrate :

Then, articles this table is created successfully.

This time you may not realize the benefits of migration, imagine the following two scenarios:

1. 在进行团队开发的时候,团队成员将我们的代码pull下来之后,怎么可以拿到一样的数据库表设计呢?难道要我们将表 export 出来,给每一个成员import一次?这显然不够明智,如果使用的migration,就一行命令,直接`php artisan migrate`,就可以拿到一样的数据库表了。2. 如果这个时候我们发现articles这个表的有一个字段写错了,比如我们的intro字段写错,它应该命名为introduction的,这个时候,我们怎么办?直接手动改数据库的表?那么回到第一个场景,你的团队成员也需要手动改?这显然也不是我们喜欢的方式,这个时候,migration的优势就来了

For example, here's a demonstration of how to solve the second scenario:

We only need command line execution:

php artisan migrate:rollback

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

$table->text(‘introduction‘);

And then do it again php artisan migrate :

Gaocheng, see the documentation for more features:

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

Using eloquent

After we have created the articles data sheet, we can write a model class for the table, you can create it manually, or you can use the Artisan command line to create a model, such as when you knock at the command line php artisan , and you see that there are a make lot of commands, and make:modelis the command we need to use:

Just like the explanation:Create a new Eloquent model class

Many times, in Laravel, we create a model with some conventional naming methods:

如果说我们有一个articles数据表,我们的model相对应就命名为Article;如果说我们有一个users的数据表,我们的model对应就命名为User;

is to basically abide by 数据表复数而model单数大写 it.

So according to this rule we create our article Model, using make:model commands:

php artisan make:model Article

In this way, our article model has been created, and this file is located blog/app/Article.php , open, to see what we laravel for us to generate:

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Article extends Model{ //}

Notice that the article class is inherited from our Eloquent\Model class, and since this Eloquent\Model class implements a lot of great ways for us to use, we can come and play happily.

The first thing to start playing is that using php artisan tinker this tool to play Around,tinker provides a command-line interface for eloquent to interact with the database table, and you can write some simple PHP operations like this:

So, let's instantiate a article:

$article = new App\Article

This equates to the instantiation of a article class, which we can do in a later operation.

When we created the table above, we had the following fields:

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

So we can use tinker it to set the $article fields above, as simple as setting properties.

For example $article , title you can set this:

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

Similarly, we can also intro set the and content field:

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

However, this is the field to note here published_at , I recommend a good time to use the library carbon, because like created_at and updated_at these two fields are also used Carbon classes, so in the subsequent processing, we will have a lot of benefits, here we first direct use of carbon:

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

And for $table->timestamps() this, Laravel will be done automatically when we insert the data, so here we can use a Eloquent save() method to insert a piece of data into the table of the database after each field is assigned articles :

$article->save();

Returns a true time, indicating that we have successfully inserted the data, let's look at the database:

Above, is a simple and complete use tinker to eloquent assignment of play process.

Let's play for a while:

All () method

all()method returns all records for article:

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

find(), accept a parameter $id, such as finding a record with ID 1:

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

You can also pass in an array of $id to find multiple records, but here we have only one piece of data, so that's it. But we can also play like this:

ToArray () Method:

To convert an eloquent object to an array:

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

ToJson () method

Convert an eloquent object to a JSON string:

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

If this is simple, eloquent is not very strong, we are writing code in the process of the where statement, this is not it?

Don't worry, this is right away:

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

When used where() , it is often necessary get() to get a Recordset, which returns a Eloquent\Collection result set, but what if I am the first day of the record to satisfy the condition?

The first() method of use, based on the above, is get() replaced by first() :

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

Here, some simple job search can be done, and for update, we can:

$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‘]);

Under normal circumstances we will get one MassAssignmentException with message :

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

This is because eloquent defaults to not allowing us to update our data directly, which is due to possible data coverage, but if we do implement such a function first, we can add an array to the article model file $fillable :

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

Then take a look at it again:

Here you need CTRL + C to exit Tinker at the time of re-entering.

Find, update, after we talk to the MassAssignmen concept of T, we can talk about create() This method, this method can be used without declaring new Article() the case to create a data, such as:

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

And then we see a strange phenomenon that we don't get the result we want:

We only have the content this field has the correct value,,, title intro There is published_at no value, why is this? MassAssignmentin fact, because of the reason, we can refer to the content of the time, in the article inside the $fillable setting of our can fill the field:

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

And then do it again:

A successful creation of the data, and then we find that the second is actually not what we want, we have to delete it:

How to use delete() :

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

We use all () to check:

It can also be used here destroy() , and this method can accept a $id or an array $ids:

App\Article::destroy(3);

Finally, let's put it. Official documents: Http://laravel.com/docs/5.1/eloquent

Laravel 5 Series Tutorial four: Databases and eloquent

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.