国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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.miracleart.cn/course/282.html

2. Learn Laravel Easily-Advanced Video Tutorial

##Related links: http://www.miracleart.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!';
});

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>

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

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

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;);
});

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

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;);
}

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

php artisan migrate

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 框架,你會發(fā)現(xiàn) Eloquent 很相似,因為它遵循數(shù)據(jù)庫交互的 ActiveRecord ORM 風格。

首先,讓我們來定義個模型。ELoquent 模型可以用來查詢相關數(shù)據(jù)表,以及表內(nèi)的某一行。別著急,我們很快會談及!模型通常存放在 app/models 目錄。讓我們在該目錄定義個 User.php 模型,如:

class User extends Eloquent {}

注意我們并沒有告訴 Eloquent 使用哪個表。Eloquent 有多種約定, 一個是使用模型的復數(shù)形式作為模型的數(shù)據(jù)庫表。非常方便!

使用你喜歡的數(shù)據(jù)庫管理工具,插入幾行數(shù)據(jù)到 users 表,我們將使用 Eloquent 取得它們并傳遞到視圖中。

現(xiàn)在我們修改我們 /users 路由如下:

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

讓我們來看看該路由。首先,User 模型的 all 方法將會從 users 表中取得所有記錄。接下來,我們通過 with 方法將這些記錄傳遞到視圖。with 方法接受一個鍵和一個值,那么該值就可以在視圖中使用了。

激動啊。現(xiàn)在我們準備將用戶顯示在我們視圖!

顯示數(shù)據(jù)

現(xiàn)在我們視圖中已經(jīng)可以訪問 users 類,我們可以如下顯示它們:


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

你可以發(fā)現(xiàn)沒有找到 echo 語句。當使用 Blade 時,你可以使用兩個花括號來輸出數(shù)據(jù)。非常簡單,你現(xiàn)在應該可以通過 /users 路由來查看到用戶姓名作為響應輸出。

下面來介紹一下如何操作數(shù)據(jù)庫:

一、讀/寫連接

有時您可能希望使用一個SELECT語句的數(shù)據(jù)庫連接,,另一個用于插入、更新和刪除語句。Laravel使這微風,將始終使用正確的連接是否使用原始查詢,查詢生成器或雄辯的ORM。

二、運行查詢

一旦你已經(jīng)配置了數(shù)據(jù)庫連接,你可以使用DB運行查詢類。

運行一個Select查詢

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

結果的選擇方法總是返回一個數(shù)組。

運行一個Insert語句

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

運行一個更新語句

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

運行一個Delete語句

DB::delete(&#39;delete from users&#39;);

注意:update和delete語句返回的行數(shù)的影響操作。

運行一個通用聲明

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

查詢事件監(jiān)聽

你可以查詢事件監(jiān)聽使用DB::聽方法:

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

三、數(shù)據(jù)庫事務

  運行在一個數(shù)據(jù)庫事務的一組操作,您可以使用事務方法:

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

注意:在事務拋出的任何異常關閉將導致自動事務將回滾

有時你可能需要開始一個事務:

DB::beginTransaction();

你可以通過回滾事務回滾方法:

DB::rollback();

最后,您可以通過提交方法:提交一個事務

DB::commit();

四、訪問連接

當使用多個連接,你可以訪問它們通過DB::連接方法:

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

你也可以訪問原始的、潛在的PDO實例:

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

有時你可能需要重新連接到一個給定的數(shù)據(jù)庫:

DB::reconnect(&#39;foo&#39;);

如果你需要斷開從給定的數(shù)據(jù)庫將超過底層PDO實例'smax_connections限制,使用斷開連接方法:

DB::disconnect(&#39;foo&#39;);

五、查詢?nèi)罩?/p>

默認情況下,Laravel日志保存在內(nèi)存的所有查詢運行當前的請求。然而,在某些情況下,例如當插入的行數(shù),這可能會導致應用程序使用多余的內(nèi)存。禁用日志,你可以使用disableQueryLog方法:

DB::connection()->disableQueryLog();

o得到一組執(zhí)行的查詢,您可以使用getQueryLog方法:

$queries = DB::getQueryLog();


相關推薦:

1. 云服務器上部署Laravel的實例教程

2.?Laravel學習-數(shù)據(jù)庫操作和查詢構造器的示例代碼分享

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

PHP Tutorial
1502
276
How to set environment variables in PHP environment Description of adding PHP running environment variables How to set environment variables in PHP environment Description of adding PHP running environment variables Jul 25, 2025 pm 08:33 PM

There are three main ways to set environment variables in PHP: 1. Global configuration through php.ini; 2. Passed through a web server (such as SetEnv of Apache or fastcgi_param of Nginx); 3. Use putenv() function in PHP scripts. Among them, php.ini is suitable for global and infrequently changing configurations, web server configuration is suitable for scenarios that need to be isolated, and putenv() is suitable for temporary variables. Persistence policies include configuration files (such as php.ini or web server configuration), .env files are loaded with dotenv library, and dynamic injection of variables in CI/CD processes. Security management sensitive information should be avoided hard-coded, and it is recommended to use.en

How to make PHP container support automatic construction? Continuously integrated CI configuration method of PHP environment How to make PHP container support automatic construction? Continuously integrated CI configuration method of PHP environment Jul 25, 2025 pm 08:54 PM

To enable PHP containers to support automatic construction, the core lies in configuring the continuous integration (CI) process. 1. Use Dockerfile to define the PHP environment, including basic image, extension installation, dependency management and permission settings; 2. Configure CI/CD tools such as GitLabCI, and define the build, test and deployment stages through the .gitlab-ci.yml file to achieve automatic construction, testing and deployment; 3. Integrate test frameworks such as PHPUnit to ensure that tests are automatically run after code changes; 4. Use automated deployment strategies such as Kubernetes to define deployment configuration through the deployment.yaml file; 5. Optimize Dockerfile and adopt multi-stage construction

What is Configuration Caching in Laravel? What is Configuration Caching in Laravel? Jul 27, 2025 am 03:54 AM

Laravel's configuration cache improves performance by merging all configuration files into a single cache file. Enabling configuration cache in a production environment can reduce I/O operations and file parsing on each request, thereby speeding up configuration loading; 1. It should be enabled when the application is deployed, the configuration is stable and no frequent changes are required; 2. After enabling, modify the configuration, you need to re-run phpartisanconfig:cache to take effect; 3. Avoid using dynamic logic or closures that depend on runtime conditions in the configuration file; 4. When troubleshooting problems, you should first clear the cache, check the .env variables and re-cache.

Explain Laravel Eloquent Scopes. Explain Laravel Eloquent Scopes. Jul 26, 2025 am 07:22 AM

Laravel's EloquentScopes is a tool that encapsulates common query logic, divided into local scope and global scope. 1. The local scope is defined with a method starting with scope and needs to be called explicitly, such as Post::published(); 2. The global scope is automatically applied to all queries, often used for soft deletion or multi-tenant systems, and the Scope interface needs to be implemented and registered in the model; 3. The scope can be equipped with parameters, such as filtering articles by year or month, and corresponding parameters are passed in when calling; 4. Pay attention to naming specifications, chain calls, temporary disabling and combination expansion when using to improve code clarity and reusability.

PHP development user permission management monetization PHP permission control and role management PHP development user permission management monetization PHP permission control and role management Jul 25, 2025 pm 06:51 PM

User permission management is the core mechanism for realizing product monetization in PHP development. It separates users, roles and permissions through a role-based access control (RBAC) model to achieve flexible permission allocation and management. The specific steps include: 1. Design three tables of users, roles, and permissions and two intermediate tables of user_roles and role_permissions; 2. Implement permission checking methods in the code such as $user->can('edit_post'); 3. Use cache to improve performance; 4. Use permission control to realize product function layering and differentiated services, thereby supporting membership system and pricing strategies; 5. Avoid the permission granularity is too coarse or too fine, and use "investment"

Essential HTML Tags for Beginners Essential HTML Tags for Beginners Jul 27, 2025 am 03:45 AM

To get started with HTML quickly, you only need to master a few basic tags to build a web skeleton. 1. The page structure is essential, and, which is the root element, contains meta information, and is the content display area. 2. Use the title. The higher the level, the smaller the number. Use tags to segment the text to avoid skipping the level. 3. The link uses tags and matches the href attributes, and the image uses tags and contains src and alt attributes. 4. The list is divided into unordered lists and ordered lists. Each entry is represented and must be nested in the list. 5. Beginners don’t have to force memorize all tags. It is more efficient to write and check them while you are writing. Master the structure, text, links, pictures and lists to create basic web pages.

How to create a helper file in Laravel? How to create a helper file in Laravel? Jul 26, 2025 am 08:58 AM

Createahelpers.phpfileinapp/HelperswithcustomfunctionslikeformatPrice,isActiveRoute,andisAdmin.2.Addthefiletothe"files"sectionofcomposer.jsonunderautoload.3.Runcomposerdump-autoloadtomakethefunctionsgloballyavailable.4.Usethehelperfunctions

How to build a log management system with PHP PHP log collection and analysis tool How to build a log management system with PHP PHP log collection and analysis tool Jul 25, 2025 pm 08:48 PM

Select logging method: In the early stage, you can use the built-in error_log() for PHP. After the project is expanded, be sure to switch to mature libraries such as Monolog, support multiple handlers and log levels, and ensure that the log contains timestamps, levels, file line numbers and error details; 2. Design storage structure: A small amount of logs can be stored in files, and if there is a large number of logs, select a database if there is a large number of analysis. Use MySQL/PostgreSQL to structured data. Elasticsearch Kibana is recommended for semi-structured/unstructured. At the same time, it is formulated for backup and regular cleaning strategies; 3. Development and analysis interface: It should have search, filtering, aggregation, and visualization functions. It can be directly integrated into Kibana, or use the PHP framework chart library to develop self-development, focusing on the simplicity and ease of interface.