Table of Contents
Laravel Quickstart
Home Backend Development PHP Tutorial 跟我学Laravel之快速入门_PHP

跟我学Laravel之快速入门_PHP

May 31, 2016 pm 07:29 PM
laravel Quick start

Laravel

安装

Laravel框架使用 Composer 执行安装和依赖管理。如果还没有安装的话,现在就开始 安装 Composer 吧。

安装Composer之后,你就可以通过命令行使用如下命令安装Laravel了:

composer create-project laravel/laravel your-project-name
或者,你可以从 Github仓库 下载。接下来,在 安装Composer 之后,在项目根目录下执行 composer install 命令。该命令将会下载以及安装框架的依赖组件。

写入权限

安装完 Laravel ,你还需要为web服务器设置 app/storage 目录的写入权限。请参考 安装 一节以获取更多关于配置方面的信息。

目录结构

安装完框架后,你需要熟悉一下该项目的目录结构。app 文件夹包含了一些例如 views ,controllers 和 models 目录。 程序中大部分代码将要存放这些目录下。你也可以查看一下 app/config 文件夹里一些配置项目。

路由

我们开始创建我们第一个路由。在 Laravel,简单路由的方法是闭包。打开 app/routes.php 文件加入如下代码:

Route::get('users', function()
{
    return 'Users!';
});
现在,你在 web 浏览器输入 /users,你应该会看到 Users! 输出。真棒!已经创建了你第一个路由。

路由也可以赋予控制器类。例如:

Route::get('users', 'UserController@getIndex');
该路由告知框架 /users 路由请求应该调用 UserController 类的 getIndex 方法。要查看更多关于路由控制器信息,查看 控制器文档 。

创建视图

接下来,我们要创建视图来显示我们用户数据。视图以HTML代码存放在 app/views 文件夹。我们将存放两个视图文件到该文件夹:layout.blade.php 和 users.blade.php。首先,让我们先创建 layout.blade.php 文件:

 

代码如下:



   


       

Laravel Quickstart

 

        @yield('content')
   

 

接着, 我们创建 users.blade.php 视图:

 

代码如下:


@extends('layout')

 

@section('content')
    Users!
@stop

 

这里的语法可能让你感到陌生。因为我们使用的是 Laravel 模板系统:Blade。Blade 非常快,因为仅使用了少量的正则表达式来为你的模板编译成原始PHP代码。Blade提供强大的功能,例如模板继承,还有一些常用的PHP控制结构语法糖,例如 if 和 for。 查看 Blade 文档 了解更多。

现在我们有了我们视图,让我们返回 /users 路由。我们用视图来替代返回 Users!:

 

代码如下:


Route::get('users', function()
{
    return View::make('users');
});

 

漂亮!现在你成功创建了继承至layout的视图。接下来,让我们开始数据库层。

创建迁移

要创建表来保存我们数据,我们将使用 Laravel 迁移系统。迁移描述数据库的改变,这让分享给他们团队成员非常简单。

首先,我们配置数据库连接。你可以在 app/config/database.php 文件配置所有数据库连接信息。默认,Laravel 被配置为使用 SQLite,并且一个 SQLite 数据库存放在 app/database 目录。你可以将数据库配置文件的 driver 选项修改为 mysql 并且配置 mysql 连接信息。

接下来,要创建迁移,我们将使用 Artisan CLI。在项目根目录中,在终端中执行以下命令:

 

代码如下:


php artisan migrate:make create_users_table

 

然后,找到生成的迁移文件 app/database/migrations 目录。该文件包含了一个包含两个方法: up 和 down 的类。在 up 方法,你要指名数据库表的修改,在 down 方法中你只需要移除它。

让我们定义如下迁移:

 

代码如下:


public function up()
{
    Schema::create('users', function($table)
    {
        $table->increments('id');
        $table->string('email')->unique();
        $table->string('name');
        $table->timestamps();
    });
}

 

public function down()
{
    Schema::drop('users');
}

 

然后,我们在项目根目录中使用终端运行 migrate 命令来执行迁移:

 

代码如下:


php artisan migrate

 

如果你想回滚迁移,你可以执行 migrate:rollback 命令。现在我们已经有了数据库表,让我们让添加一些数据!

Eloquent ORM

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

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

 

代码如下:


class User extends Eloquent {}

 

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

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

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

 

代码如下:


Route::get('users', function()
{
    $users = User::all();

 

    return View::make('users')->with('users', $users);
});

 

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

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

显示数据

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

 

代码如下:


@extends('layout')

 

@section('content')
    @foreach($users as $user)
       

{{ $user->name }}


    @endforeach
@stop

 

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

这仅仅是开始。在本系列教程中,你已经了解了 Laravel 基础部分,但是还有更让人兴奋的东西要学。继续阅读该文档并且深入Eloquent和Blade这些强大的特性。或者你对队列 和 单元测试 感兴趣。或许是你想了解IoC Container, 选择权在于你!

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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)

PHP vs. Flutter: The best choice for mobile development PHP vs. Flutter: The best choice for mobile development May 06, 2024 pm 10:45 PM

PHP and Flutter are popular technologies for mobile development. Flutter excels in cross-platform capabilities, performance and user interface, and is suitable for applications that require high performance, cross-platform and customized UI. PHP is suitable for server-side applications with lower performance and not cross-platform.

How to use object-relational mapping (ORM) in PHP to simplify database operations? How to use object-relational mapping (ORM) in PHP to simplify database operations? May 07, 2024 am 08:39 AM

Database operations in PHP are simplified using ORM, which maps objects into relational databases. EloquentORM in Laravel allows you to interact with the database using object-oriented syntax. You can use ORM by defining model classes, using Eloquent methods, or building a blog system in practice.

Analysis of the advantages and disadvantages of PHP unit testing tools Analysis of the advantages and disadvantages of PHP unit testing tools May 06, 2024 pm 10:51 PM

PHP unit testing tool analysis: PHPUnit: suitable for large projects, provides comprehensive functionality and is easy to install, but may be verbose and slow. PHPUnitWrapper: suitable for small projects, easy to use, optimized for Lumen/Laravel, but has limited functionality, does not provide code coverage analysis, and has limited community support.

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 ?

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.

How do the data processing capabilities in Laravel and CodeIgniter compare? How do the data processing capabilities in Laravel and CodeIgniter compare? Jun 01, 2024 pm 01:34 PM

Compare the data processing capabilities of Laravel and CodeIgniter: ORM: Laravel uses EloquentORM, which provides class-object relational mapping, while CodeIgniter uses ActiveRecord to represent the database model as a subclass of PHP classes. Query builder: Laravel has a flexible chained query API, while CodeIgniter’s query builder is simpler and array-based. Data validation: Laravel provides a Validator class that supports custom validation rules, while CodeIgniter has less built-in validation functions and requires manual coding of custom rules. Practical case: User registration example shows Lar

PHP code unit testing and integration testing PHP code unit testing and integration testing May 07, 2024 am 08:00 AM

PHP Unit and Integration Testing Guide Unit Testing: Focus on a single unit of code or function and use PHPUnit to create test case classes for verification. Integration testing: Pay attention to how multiple code units work together, and use PHPUnit's setUp() and tearDown() methods to set up and clean up the test environment. Practical case: Use PHPUnit to perform unit and integration testing in Laravel applications, including creating databases, starting servers, and writing test code.

Laravel vs CodeIgniter: Which framework is better for large projects? Laravel vs CodeIgniter: Which framework is better for large projects? Jun 04, 2024 am 09:09 AM

When choosing a framework for large projects, Laravel and CodeIgniter each have their own advantages. Laravel is designed for enterprise-level applications, offering modular design, dependency injection, and a powerful feature set. CodeIgniter is a lightweight framework more suitable for small to medium-sized projects, emphasizing speed and ease of use. For large projects with complex requirements and a large number of users, Laravel's power and scalability are more suitable. For simple projects or situations with limited resources, CodeIgniter's lightweight and rapid development capabilities are more ideal.

See all articles