search
HomeBackend DevelopmentPHP TutorialLaravel 5 框架入门(一)_php实例

Laravel 5 中文文档:

1. http://laravel-china.org/docs/5.0

2. http://www.golaravel.com/laravel/docs/5.0/

默认条件

本文默认你已经有配置完善的 PHP + MySQL 运行环境,懂得 PHP 网站运行的基础知识。跟随本教程走完一遍,你将会得到一个基础的包含登录的简单 blog 系统,并将学会如何使用一些强大的 Laravel 插件和 composer 包(Laravel 插件也是 composer 包)。

软件版本:PHP 5.4+,MySQL 5.1+

本文不推荐完全不懂 PHP 与 MVC 编程的人学习。本文不是 “一步一步跟我做” 教程。本文需要你付出一定的心智去解决一些或大或小的隐藏任务,以达到真正理解 Laravel 运行逻辑的目的。

1. 安装

许多人被拦在了学习Laravel的第一步,安装。并不是因为安装教程有多复杂,而是因为【众所周知的原因】。在此我推荐一个composer全量中国镜像:http://pkg.phpcomposer.com/ 。推荐以 “修改 composer 的配置文件” 方式配置。

镜像配置完成后,切换到你想要放置该网站的目录下(如 C:\\wwwroot、/Library/WebServer/Documents/、/var/www/html、/etc/nginx/html 等),运行命令:

composer create-project laravel/laravel learnlaravel5

然后,稍等片刻,当前目录下就会出现一个叫 learnlaravel5 的文件夹。

然后将网站根目录配置为 learnlaravel5/public。

如果你不会配置,建议去学会配置,网上资料很多。如果自暴自弃,可以把 的第 29 行'url' => 'http://localhost', 配置成你的子目录地址,注意,要一直配置到 ***/learnlaravel5/public。

使用浏览器访问你配置的地址,将看到以下画面(我在本地配置的地址为 http://fuck.io:88 ):


2. 体验 Auth 系统并完成安装

—— 经过上面的过程,Laravel 5 的安装成功了?

—— 没有o(╯□╰)o

查看路由文件 `learnlaravel5/app/Http/routes.php` 的代码:

Route::get('/', 'WelcomeController@index');

Route::get('home', 'HomeController@index');

Route::controllers([
	'auth' => 'Auth\AuthController',
	'password' => 'Auth\PasswordController',
]);

跟随代码里的蛛丝马迹,让我们访问 http://fuck.io:88/home (请自行替换域名),结果竟然跳转到了登陆页?


没错,Laravel 自带了开箱即用的 Auth 系统,连页面都已经写好了。

让我们随意输入邮箱和密码,点击登录,你很可能得到以下画面(Mac 或 Linux 下):


为什么空白?用开发者工具查看,这个请求的状态码是 500,为什么?

因为 `learnlaravel5/storage` 目录没有 777 权限。

执行 shell 命令:

cd learnlaravel5

sudo chmod -R 777 storage

重新访问 http://fuck.io:88/home ,随意输入邮箱和密码,如果你得到以下画面:


那么恭喜你~ Laravel 5 安装成功!

不想配置镜像的同学,可以使用 Laravel 界非常著名的 安正超 搞的安装神器:https://github.com/overtrue/latest-laravel

3. 数据库建立及迁移

Laravel 5 把数据库配置的地方改到了 `learnlaravel5/.env`,打开这个文件,编辑下面四项,修改为正确的信息:

DB_HOST=localhost

DB_DATABASE=laravel5

DB_USERNAME=root

DB_PASSWORD=password

推荐新建一个名为 laravel5 的数据库,为了学习方便,推荐使用 root 账户直接操作。

Laravel 已经为我们准备好了 Auth 部分的 migration,运行以下命令执行数据库迁移操作:

php artisan migrate

得到的结果如下:


如果你运行命令报错,请检查数据库连接设置。

至此,数据库迁移已完成,你可以打开 http://fuck.io:88/home 欢快地尝试注册、登录啦。

4. 模型 Models

接下来我们将接触Laravel最为强大的部分,Eloquent ORM,真正提高生产力的地方,借用库克的一句话:鹅妹子英!

运行一下命令:

php artisan make:model Article

php artisan make:model Page

> Laravel 4 时代,我们使用 Generator 插件来新建 Model。现在,Laravel 5 已经把 Generator 集成进了 Artisan。

现在,Artisan 帮我们在 `learnlaravel5/app/` 下创建了两个文件 `Article.php` 和 `Page.php`,这是两个 Model 类,他们都继承了 Laravel Eloquent 提供的 Model 类 `Illuminate\Database\Eloquent\Model`,且都在 `\App` 命名空间下。这里需要强调一下,用命令行的方式创建文件,和自己手动创建文件没有任何区别,你也可以尝试自己创建这两个 Model 类。

Model 即为 MVC 中的 M,翻译为 模型,负责跟数据库交互。在 Eloquent 中,数据库中每一张表对应着一个 Model 类(当然也可以对应多个)。

如果你从其他框架转过来,可能对这里一笔带过的 Model 部分很不适应,没办法,是因为 Eloquent 实在太强大了啦,真的没什么好做的,继承一下 Eloquent 类就能实现很多很多功能了。

如果你想深入地了解 Eloquent,可以阅读系列文章:Laravel 5框架学习之Eloquent 关系

接下来进行 Article 和 Page 类对应的 articles 表和 pages表的数据库迁移,进入 `learnlaravel5/database/migrations` 文件夹。

在 ***_create_articles_table.php 中修改:

Schema::create('articles', function(Blueprint $table)
{
	$table->increments('id');
	$table->string('title');
	$table->string('slug')->nullable();
	$table->text('body')->nullable();
	$table->string('image')->nullable();
	$table->integer('user_id');
	$table->timestamps();
});

在 ***_create_pages_table.php 中修改:

Schema::create('pages', function(Blueprint $table)
{
	$table->increments('id');
	$table->string('title');
	$table->string('slug')->nullable();
	$table->text('body')->nullable();
	$table->integer('user_id');
	$table->timestamps();
});

然后执行命令:

php artisan migrate

成功以后, tables 表和 pages 表已经出现在了数据库里,去看看吧~

5. 数据库填充 Seeder

在 `learnlaravel5/database/seeds/` 下新建 `PageTableSeeder.php` 文件,内容如下:

<&#63;php

use Illuminate\Database\Seeder;
use App\Page;

class PageTableSeeder extends Seeder {

 public function run()
 {
  DB::table('pages')->delete();

  for ($i=0; $i < 10; $i++) {
   Page::create([
    'title'  => 'Title '.$i,
    'slug'  => 'first-page',
    'body'  => 'Body '.$i,
    'user_id' => 1,
   ]);
  }
 }

}

然后修改同一级目录下的 `DatabaseSeeder.php`中:

// $this->call('UserTableSeeder');

这一句为

$this->call('PageTableSeeder');

然后运行命令进行数据填充:

composer dump-autoloadphp artisan db:seed

去看看 pages 表,是不是多了十行数据?

本教程示例代码见:https://github.com/johnlui/Learn-Laravel-5

大家在任何地方卡住,最快捷的解决方式就是去看我的示例代码。

以上所述就是本文的全部内容了,希望能够对大家学习Laravel5框架有所帮助。

Statement
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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in LaravelNotifications in LaravelMar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft