Home > headlines > body text

Laravel tutorial basics and how to operate the database

伊谢尔伦
Release: 2017-07-10 11:51:13
Original
1799 people have browsed it

Laravel is the most elegant PHP framework. Many friends who are learning PHP have long been coveted by Laravel. Let us start from scratch and teach you how to install and use its basic functions, as well as database operations. Today our php Chinese website will bring you some learning and practice.

You can learn the video tutorial provided by php Chinese website:

1. Easy to learn Laravel - Basics

Related links: http://www.php.cn/course/282.html

2. Learn Laravel Easily-Advanced Video Tutorial

##Related links: http://www.php.cn/course /402.html

Let’s start learning and using the Laravel framework!

Installation

The Laravel framework uses Composer to perform installation and dependency management. If you haven't installed it yet, start installing Composer now.

After installing Composer, you can install Laravel through the command line using the following command:

composer create-project laravel/laravel your-project-name

Alternatively, you can install it from Github Warehouse download. Next, after installing Composer, execute the composer install command in the project root directory. This command will download and install the framework's dependent components.

Write permission

Directory structure

After installing the framework, you need to familiarize yourself with it The directory structure of the project. The app folder contains directories such as views, controllers, and models. Most of the code in the program will be stored in these directories. You can also check some configuration items in the app/config folder.

Routing

We start creating our first route. In Laravel, the simple way to route is with closures. Open the app/routes.php file and add the following code:

Route::get('users', function()
{
    return 'Users!';
});
Copy after login

Now, when you type /users in your web browser, you should see Users! output. Awesome! Your first route has been created.


Routes can also be assigned to controller classes. For example:

Create a view

Next, we need to create a view to display our user data. Views are stored in the app/views folder as HTML code. We will place two view files into this folder: layout.blade.php and users.blade.php. First, let's create the layout.blade.php file:

<html>
    <body>
        <h1>Laravel Quickstart</h1>
                @yield(&#39;content&#39;)
    </body>
</html>
Copy after login

Next, we create the users.blade.php view:

@extends(&#39;layout&#39;)
@section(&#39;content&#39;)    
Users!
@stop
Copy after login

The syntax here may be unfamiliar to you. Because we are using Laravel's template system: Blade. Blade is very fast because only a small amount of

regex is used to compile your templates into raw PHP code. Blade provides powerful features, such as template inheritance, as well as some common PHP control structure syntax sugar, such as if and for. Check out the Blade documentation to learn more.

Now that we have our view, let’s return to the /users route. We use a view instead to return Users!:

Route::get(&#39;users&#39;, function()
{
    return View::make(&#39;users&#39;);
});
Copy after login

Beautiful! Now you have successfully created a view that inherits from layout. Next, let's start with the database layer.

Create Migration

To create the table to hold our data, we will use the Laravel migration system. Migrations describe changes to a database, making it easy to share them with team members.

First, we configure the database connection. You can configure all database connection information in the app/config/database.php file. By default, Laravel is configured to use SQLite, and a SQLite database is stored in the app/database directory. You can modify the driver option of the database

configuration file to mysql and configure the mysql connection information.

Next, to create the migration, we will use the Artisan CLI. In the project root directory, execute the following command in the terminal:

php artisan migrate:make create_users_table
Copy after login

Then, locate the generated migration files in the app/database/migrations directory. This file contains a class with two methods: up and down. In the up method, you name the modification to the database table, and in the down method you just remove it.

Let us define the migration as follows:

public function up()
{
    Schema::create(&#39;users&#39;, function($table)
    {
        $table->increments(&#39;id&#39;);
        $table->string(&#39;email&#39;)->unique();
        $table->string(&#39;name&#39;);
        $table->timestamps();
    });
}
public function down()
{
    Schema::drop(&#39;users&#39;);
}
Copy after login

Then, we run the migrate command in the project root directory using the terminal to execute the migration:

php artisan migrate
Copy after login

If you want to roll back the migration, You can execute the migrate:rollback command. Now that we have our database table, let's add some data!

Eloquent ORM

Laravel 提供非常棒的 ORM:Eloquent。如果你使用过 Ruby on Rails 框架,你会发现 Eloquent 很相似,因为它遵循数据库交互的 ActiveRecord ORM 风格。

首先,让我们来定义个模型。ELoquent 模型可以用来查询相关数据表,以及表内的某一行。别着急,我们很快会谈及!模型通常存放在 app/models 目录。让我们在该目录定义个 User.php 模型,如:

class User extends Eloquent {}
Copy after login

注意我们并没有告诉 Eloquent 使用哪个表。Eloquent 有多种约定, 一个是使用模型的复数形式作为模型的数据库表。非常方便!

使用你喜欢的数据库管理工具,插入几行数据到 users 表,我们将使用 Eloquent 取得它们并传递到视图中。

现在我们修改我们 /users 路由如下:

Route::get(&#39;users&#39;, function()
{
    $users = User::all();
    return View::make(&#39;users&#39;)->with(&#39;users&#39;, $users);
});
Copy after login

让我们来看看该路由。首先,User 模型的 all 方法将会从 users 表中取得所有记录。接下来,我们通过 with 方法将这些记录传递到视图。with 方法接受一个键和一个值,那么该值就可以在视图中使用了。

激动啊。现在我们准备将用户显示在我们视图!

显示数据

现在我们视图中已经可以访问 users 类,我们可以如下显示它们:


@extends(&#39;layout&#39;)
@section(&#39;content&#39;)
    @foreach($users as $user)
        <p>{{ $user->name }}</p>
    @endforeach
@stop
Copy after login

你可以发现没有找到 echo 语句。当使用 Blade 时,你可以使用两个花括号来输出数据。非常简单,你现在应该可以通过 /users 路由来查看到用户姓名作为响应输出。

下面来介绍一下如何操作数据库:

一、读/写连接

有时您可能希望使用一个SELECT语句的数据库连接,,另一个用于插入、更新和删除语句。Laravel使这微风,将始终使用正确的连接是否使用原始查询,查询生成器或雄辩的ORM。

二、运行查询

一旦你已经配置了数据库连接,你可以使用DB运行查询类。

运行一个Select查询

$results = DB::select(&#39;select * from users where id = ?&#39;, array(1));
Copy after login

结果的选择方法总是返回一个数组。

运行一个Insert语句

DB::insert(&#39;insert into users (id, name) values (?, ?)&#39;, array(1, &#39;Dayle&#39;));
Copy after login

运行一个更新语句

DB::update(&#39;update users set votes = 100 where name = ?&#39;, array(&#39;John&#39;));
Copy after login

运行一个Delete语句

DB::delete(&#39;delete from users&#39;);
Copy after login

注意:update和delete语句返回的行数的影响操作。

运行一个通用声明

DB::statement(&#39;drop table users&#39;);
Copy after login

查询事件监听

你可以查询事件监听使用DB::听方法:

DB::listen(function($sql, $bindings, $time){ //});
Copy after login

三、数据库事务

  运行在一个数据库事务的一组操作,您可以使用事务方法:

 DB::transaction(function(){ DB::table(&#39;users&#39;)->update(array(&#39;votes&#39; => 1)); DB::table(&#39;posts&#39;)->delete();});
Copy after login

注意:在事务抛出的任何异常关闭将导致自动事务将回滚

有时你可能需要开始一个事务:

DB::beginTransaction();
Copy after login

你可以通过回滚事务回滚方法:

DB::rollback();
Copy after login

最后,您可以通过提交方法:提交一个事务

DB::commit();
Copy after login

四、访问连接

当使用多个连接,你可以访问它们通过DB::连接方法:

$users = DB::connection(&#39;foo&#39;)->select(...);
Copy after login

你也可以访问原始的、潜在的PDO实例:

$pdo = DB::connection()->getPdo();
Copy after login

有时你可能需要重新连接到一个给定的数据库:

DB::reconnect(&#39;foo&#39;);
Copy after login

如果你需要断开从给定的数据库将超过底层PDO实例'smax_connections限制,使用断开连接方法:

DB::disconnect(&#39;foo&#39;);
Copy after login

五、查询日志

默认情况下,Laravel日志保存在内存的所有查询运行当前的请求。然而,在某些情况下,例如当插入的行数,这可能会导致应用程序使用多余的内存。禁用日志,你可以使用disableQueryLog方法:

DB::connection()->disableQueryLog();
Copy after login

o得到一组执行的查询,您可以使用getQueryLog方法:

$queries = DB::getQueryLog();
Copy after login


相关推荐:

1. 云服务器上部署Laravel的实例教程

2. Laravel学习-数据库操作和查询构造器的示例代码分享

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template