Home headlines Laravel tutorial basics and how to operate the database

Laravel tutorial basics and how to operate the database

Jul 10, 2017 am 11:51 AM
laravel getting Started how

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学习-数据库操作和查询构造器的示例代码分享

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Generate PPT with one click! Kimi: Let the 'PPT migrant workers' become popular first Generate PPT with one click! Kimi: Let the 'PPT migrant workers' become popular first Aug 01, 2024 pm 03:28 PM

Kimi: In just one sentence, in just ten seconds, a PPT will be ready. PPT is so annoying! To hold a meeting, you need to have a PPT; to write a weekly report, you need to have a PPT; to make an investment, you need to show a PPT; even when you accuse someone of cheating, you have to send a PPT. College is more like studying a PPT major. You watch PPT in class and do PPT after class. Perhaps, when Dennis Austin invented PPT 37 years ago, he did not expect that one day PPT would become so widespread. Talking about our hard experience of making PPT brings tears to our eyes. "It took three months to make a PPT of more than 20 pages, and I revised it dozens of times. I felt like vomiting when I saw the PPT." "At my peak, I did five PPTs a day, and even my breathing was PPT." If you have an impromptu meeting, you should do it

All CVPR 2024 awards announced! Nearly 10,000 people attended the conference offline, and a Chinese researcher from Google won the best paper award All CVPR 2024 awards announced! Nearly 10,000 people attended the conference offline, and a Chinese researcher from Google won the best paper award Jun 20, 2024 pm 05:43 PM

In the early morning of June 20th, Beijing time, CVPR2024, the top international computer vision conference held in Seattle, officially announced the best paper and other awards. This year, a total of 10 papers won awards, including 2 best papers and 2 best student papers. In addition, there were 2 best paper nominations and 4 best student paper nominations. The top conference in the field of computer vision (CV) is CVPR, which attracts a large number of research institutions and universities every year. According to statistics, a total of 11,532 papers were submitted this year, and 2,719 were accepted, with an acceptance rate of 23.6%. According to Georgia Institute of Technology’s statistical analysis of CVPR2024 data, from the perspective of research topics, the largest number of papers is image and video synthesis and generation (Imageandvideosyn

From bare metal to a large model with 70 billion parameters, here is a tutorial and ready-to-use scripts From bare metal to a large model with 70 billion parameters, here is a tutorial and ready-to-use scripts Jul 24, 2024 pm 08:13 PM

We know that LLM is trained on large-scale computer clusters using massive data. This site has introduced many methods and technologies used to assist and improve the LLM training process. Today, what we want to share is an article that goes deep into the underlying technology and introduces how to turn a bunch of "bare metals" without even an operating system into a computer cluster for training LLM. This article comes from Imbue, an AI startup that strives to achieve general intelligence by understanding how machines think. Of course, turning a bunch of "bare metal" without an operating system into a computer cluster for training LLM is not an easy process, full of exploration and trial and error, but Imbue finally successfully trained an LLM with 70 billion parameters. and in the process accumulate

AI in use | AI created a life vlog of a girl living alone, which received tens of thousands of likes in 3 days AI in use | AI created a life vlog of a girl living alone, which received tens of thousands of likes in 3 days Aug 07, 2024 pm 10:53 PM

Editor of the Machine Power Report: Yang Wen The wave of artificial intelligence represented by large models and AIGC has been quietly changing the way we live and work, but most people still don’t know how to use it. Therefore, we have launched the "AI in Use" column to introduce in detail how to use AI through intuitive, interesting and concise artificial intelligence use cases and stimulate everyone's thinking. We also welcome readers to submit innovative, hands-on use cases. Video link: https://mp.weixin.qq.com/s/2hX_i7li3RqdE4u016yGhQ Recently, the life vlog of a girl living alone became popular on Xiaohongshu. An illustration-style animation, coupled with a few healing words, can be easily picked up in just a few days.

Counting down the 12 pain points of RAG, NVIDIA senior architect teaches solutions Counting down the 12 pain points of RAG, NVIDIA senior architect teaches solutions Jul 11, 2024 pm 01:53 PM

Retrieval-augmented generation (RAG) is a technique that uses retrieval to boost language models. Specifically, before a language model generates an answer, it retrieves relevant information from an extensive document database and then uses this information to guide the generation process. This technology can greatly improve the accuracy and relevance of content, effectively alleviate the problem of hallucinations, increase the speed of knowledge update, and enhance the traceability of content generation. RAG is undoubtedly one of the most exciting areas of artificial intelligence research. For more details about RAG, please refer to the column article on this site "What are the new developments in RAG, which specializes in making up for the shortcomings of large models?" This review explains it clearly." But RAG is not perfect, and users often encounter some "pain points" when using it. Recently, NVIDIA’s advanced generative AI solution

Comparison of the latest versions of Laravel and CodeIgniter Comparison of the latest versions of Laravel and CodeIgniter Jun 05, 2024 pm 05:29 PM

The latest versions of Laravel 9 and CodeIgniter 4 provide updated features and improvements. Laravel9 adopts MVC architecture and provides functions such as database migration, authentication and template engine. CodeIgniter4 uses HMVC architecture to provide routing, ORM and caching. In terms of performance, Laravel9's service provider-based design pattern and CodeIgniter4's lightweight framework give it excellent performance. In practical applications, Laravel9 is suitable for complex projects that require flexibility and powerful functions, while CodeIgniter4 is suitable for rapid development and small applications.

Another Sora-level player is coming to hit the streets! We compared it with Sora and Keling. Another Sora-level player is coming to hit the streets! We compared it with Sora and Keling. Aug 02, 2024 am 10:19 AM

When Sora failed to come out, OpenAI's opponents used their weapons to destroy the streets. If Sora is not open for use, it will really be stolen! Today, San Francisco startup LumaAI played a trump card and launched a new generation of AI video generation model DreamMachine. Free and available to everyone. According to reports, the model can generate high-quality, realistic videos based on simple text descriptions, with effects comparable to Sora. As soon as the news came out, a large number of users crowded into the official website to try it out. Although officials claim that the model can generate 120-frame video in just two minutes, many users have been waiting for hours on the official website due to a surge in visits. BarkleyDai, Luma’s head of product growth, had to comment on Discord

Laravel - Artisan Commands Laravel - Artisan Commands Aug 27, 2024 am 10:51 AM

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?