get started with laravel
Browsing the API (http://laravel.com/api) can be somewhat intimidating at first.
But it is often the best way to understand how a particular method works under the
hood. Here are a few tips:
• The Illuminate namespace does not refer to a third-party library. It is the
namespace that the author of Laravel has chosen for the different modules
that constitute Laravel. Every single one of them is meant to be reusable and
used independently from the framework.
• When searching for a class definition, for example, Auth, in the source code
or the API, you might bump into Façade, which hardly contains any helpful
method and only acts as a proxy to the real class. This is because almost
every dependency in Laravel is injected into the application container when
it is instantiated.
• Most of the libraries that are included in the vendor/ directory contain a
README file, which details the functionality present in the library (for
example, vendor/nesbot/carbon/readme.md).
If, on the other hand, you have not worked with RESTful sites, the use of the PUT
and DELETE HTTP methods might be new to you. Even though web browsers do
not support these methods for standard HTTP requests, Laravel uses a technique
that other frameworks such as Rails use, and emulates those methods by adding
a _method input field to the forms. This way, they can be sent over a standard
POST request and are then delegated to the correct route or controller method
in the application.
Using the built-in development server
To start the application, unless you are running an older version of PHP (5.3.*), you
will not need a local server such as WAMP on Windows or MAMP on Mac OS since
Laravel uses the built-in development server that is bundled with PHP 5.4 or later.
To start the development server, we use the following artisan command:
$ php artisan serve
Artisan is the command-line utility that ships with Laravel and its features will be
covered in more detail in a future chapter.
Next, open your web browser and visit http://localhost:8000; you will be
greeted with Laravel's welcome message.
Catching the missing routes
Instead of displaying a detailed error message to your visitors, you can catch the
"Not Found" exception and display a custom message by defining the following
missing method for your application inside app/start/global.php:
App::missing(function($exception){
return Response::make("Page not found", 404);
});
Here we are not merely returning a string, but a Response object with the message
as its first parameter and an HTTP status code as the second parameter. In the
first two routes that we wrote, Laravel automatically converted the string that
we returned into a 200 OK HTTP response (for example, in the first route it is:
Response::make("All cats", 200)). While the difference might not be obvious
to the end users, the distinction between "404 Not Found" and "200 OK" is important
for the search engines that crawl your site or when you are writing an API.
Handling redirections
It is also possible to redirect visitors by returning a Redirect object from your
routes. If for example, we wanted everyone to be redirected to /cats when they
visit the application for the first time, we would write the following lines of code:
Route::get('/', function(){
return Redirect::to('cats');
});
Route::get('cats', function(){
return "All cats";
});
Creating the Eloquent models
The first and easiest step is to define the models with which our application is going
to interact. At the beginning of this chapter, we identified two main entities, cats
and breeds. Laravel ships with Eloquent, a powerful ORM that lets you define these
entities, map them to their corresponding database tables, and interact with them
using PHP methods rather than raw SQL. By convention, they are written in the
singular form; a model named Cat will map to the cats table in the database,
and a hypothetical Mouse model will map to the mice.
The Cat model, saved inside app/models/Cat.php, will have a belongsTo
relationship with the Breed model, which is defined in the following code snippet:
class Cat extends Eloquent {
protected $fillable = array('name','date_of_birth','breed_id');
public function breed(){
return $this->belongsTo('Breed');
}
}
The $fillable array defines the list of fields that Laravel can fill by mass
assignment, a convenient way to assign attributes to a model. By convention, the
column that Laravel will use to find the related model has to be called breed_id in
the database. The Breed model, app/models/Breed.php is defined with the inverse
hasMany relationship as follows:
class Breed extends Eloquent {
public $timestamps = false;
public function cats(){
return $this->hasMany('Cat');
}
}
By default, Laravel expects a created_at and updated_at timestamp field in the
database table. Since we are not interested in storing these timestamps with the
breeds, we disable them in the model by setting the $timestamps property to false.
This is all the code that is required in our models for now. We will discover various
other features of Eloquent as we progress in this book; however, in this chapter we
will primarily use two methods: all() and find(). To illustrate their purpose,
here are the SQL queries that they generate:
Breed::all() => SELECT * FROM breeds;
Cat::find(1) => SELECT * FROM cats WHERE id = 1;
In the views and controllers of our application, the properties of an Eloquent model
can be retrieved with the -> operator: $cat->name. The same goes for the properties
of the related models, which are accessible as shown: $cat->breed->name. Behind
the scenes, Eloquent will perform the necessary SQL joins.
Building the database schema
Now that we have defined our models, we need to create the corresponding database
schema. Thanks to Laravel's support for migrations and its powerful schema builder,
you will not have to write any SQL code and you will also be able to keep track of
any schema changes in a version control system. To create your first migration,
open a new terminal window, and enter the following command:
$ php artisan migrate:make add_cats_and_breeds_table
This will create a new migration inside app/database/migrations/. If you open
the newly created file, you will find some code that Laravel has generated for
you. Migrations always have an up() and down() method that defines the schema
changes when migrating up or down. By convention, the table and field names are
written in "snake_case". Moreover, the table names are written in the plural form.
our first migration looks like this:
public function up(){
Schema::create('cats', function($table){
$table->increments('id');
$table->string('name');
$table->date('date_of_birth');
$table->integer('breed_id')->nullable();
$table->timestamps();
});
Schema::create('breeds', function($table){
$table->increments('id');
$table->string('name');
});
}
public function down(){
Schema::drop('cats');
Schema::drop('breeds');
}
The date() and string() methods create fields with the corresponding types
(in this case, DATE and VARCHAR) in the database, increments() creates an auto
incrementing INTEGER primary key, and timestamps() adds the created_at and
updated_at DATETIME fields that Eloquent expects by default. The nullable()
method specifies that the column can have NULL values.
To run the migration, enter the following command:
$ php artisan migrate
When it is run for the first time, this command will also create a migrations table
that Laravel uses to keep track of the migrations that have been run.
Seeding the database 播种
Rather than manually populating our database, we can use the seeding helpers
offered by Laravel. This time, there is no Artisan command to generate the file,
but all we need to do is create a new class called BreedsTableSeeder.php inside
app/database/seeds/. This class extends Laravel's Seeder class and defines the
following run() method:
<?php
use Illuminate\Database\Seeder;
class BreedsTableSeeder extends Seeder
{
public function run()
{
DB::table('breeds')->insert(array(
array('id'=>1,'name'=>'Domestic'),
array('id'=>2, 'name'=>"Persian"),
array('id'=>3, 'name'=>"Siamese"),
array('id'=>4, 'name'=>"Abyssinian"),
)); }
}
You can bulk insert an array but you could also insert arbitrary code in the run()
method to load data from a CSV or JSON file. There are also third-party libraries
that can help you generate large amounts of test data to fill your database.
To control the order of execution of the seeders, Laravel lets you call them
individually inside app/database/seeds/DatabaseSeeder.php. In our case,
since we only have one seeder, all we need to write is the line that follows:
$this->call('BreedsTableSeeder');
Then, we can seed the database by calling it using the following command:
$ php artisan db:seed
Mastering Blade
Now that we have some information in our database, we need to define the
templates that are going to display it. Blade is Laravel's lightweight template
language and its syntax is very easy to learn. Here are some examples of how Blade
can reduce the number of keystrokes and increase the readability of your templates:
Standard PHP syntax Blade syntax
<?php echo $var; ?> {{$var}}
<?php echo htmlentities($var); ?> {{{$var}}}
<?php if($cond): ?>…<?php endif; ?> @if($cond) … @endif
You should only use the double braces to output a variable if you trust the user
or the value that is returned. In all other cases, make sure that you use the triple
brace notation to avoid XSS vulnerabilities (explained in a bit more detail in the
next chapter).
Blade supports all of PHP's major constructs to create loops and conditions: @for,
@foreach, @while, @if, and @elseif; therefore, allowing you to avoid opening
and closing the <?php tags everywhere in your templates
Creating a master view
Blade lets you build hierarchical layouts by allowing the templates to be nested and
extended. The following code snippet is the "master" template that we are going to
use for our application. We will save it as app/views/master.blade.php.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cats DB</title>
<link rel="stylesheet" href="{{asset('bootstrap-3.0.0.min.
css')}}">
</head>
<body>
<div class="container">
<div class="page-header">
@yield('header')
</div>
@if(Session::has('message'))
<div class="alert alert-success">
{{Session::get('message')}}
</div>
@endif
@yield('content')
</div>
</body>
</html>
The Bootstrap 3 CSS framework is included to speed up the prototyping of the
application interface. You can download it from http://getbootstrap.com and
place the minified CSS file inside the public/ folder. To ensure that its path prefix is
set correctly, even when Laravel is run from a subfolder, we use the asset() helper.
In the following template, we will use other helpers such as url and link_to, which
help us write more concise code and also escape from any HTML entities. To
see the complete list of Blade template helpers that are available to you, visit:
http://laravel.com/docs/helpers.
To inform the user about the outcome of certain actions, we have prepared a
notification area between the header and the page content. This flash data (in other
words, the session data that is only available for the next request) is passed and
retrieved to and from the Session object.
The @yield directives act as placeholders for the different sections that a child
view can populate and override. To see how a child template can re-use them, we
are going to recreate the About view by changing its extension to .blade.php and
extending our master template:
@extends('master')
@section('header')
<h2>About this site</h2>
@stop
@section('content')
<p>There are over {{$number_of_cats}} cats on this site!</p>
@stop
The @section ... @stop directives delimit the blocks of content that are going
to be injected into the master template。
The next set of routes will handle the three different types of actions and redirect
the user using a flash data message. This message is then retrieved in the Session
object using Session::get('message') in the master template. Any input data
that is received by the application and that you would normally access via the $_GET
or $_POST variables is instead retrievable using the Input::get() method. It is also
possible to retrieve an array of all the input data with Input::all(). They also use
more features of Eloquent that we have not seen before. The POST /cats and PUT /
cats/{cat} routes, respectively, use the create() and update() methods from
Eloquent with Input::all() as their argument. This is only possible because we
specified the specific fields that are fillable in the Cat model beforehand:
get started with laravel的更多相关文章
- TODO:Laravel增加验证码
TODO:Laravel增加验证码1. 先聊聊验证码是什么,有什么作用?验证码(CAPTCHA)是"Completely Automated Public Turing test to te ...
- TODO:Laravel 内置简单登录
TODO:Laravel 内置简单登录 1. 激活Laravel的Auth系统Laravel 利用 PHP 的新特性 trait 内置了非常完善好用的简单用户登录注册功能,适合一些不需要复杂用户权限管 ...
- TODO:Laravel 使用blade标签布局页面
TODO:Laravel 使用blade标签布局页面 本文主要介绍Laravel的标签使用,统一布局页面.主要用到到标签有@yield,@ stack,@extends,@section,@stop, ...
- TODO:搭建Laravel VueJS SemanticUI
TODO:搭建Laravel VueJS SemanticUI Laravel是一套简洁.优雅的PHP开发框架(PHP Web Framework).可以让你从面条一样杂乱的代码中解脱出来:它可以帮你 ...
- Bringing Whoops Back to Laravel 5
You might be missing the "prettier" Whoops error handler from Laravel 4. If so, here's how ...
- 在 Laravel 中使用图片处理库 Integration/Image
系统需求 PHP >= 5.3 Fileinfo Extension GD Library (>=2.0) … or … Imagick PHP extension (>=6.5.7 ...
- Laravel Composer and ServiceProvider
Composer and: 创建自定义类库时,按命名空间把文件夹结构组织好 composer.json>autoload>classmap>psr-4 composer dump-a ...
- Laravel 5.x 请求的生命周期(附源码)
Laravel最早接触是刚开始实习的时候,那时通过网上的学习资料很快便上手,开发模块接口.后来没有什么深入和总结,但是当我刚开始学Laravel的时候,我对Laravel最大的认识就是,框架除了路由. ...
- Laravel 5.3 登录注册底层实现详解
每个控制器都使用 trait 来引入它们需要的方法 */ 用于处理用户登录认证 用于处理新用户注册 包含重置密码逻辑 用于处理重置密码邮件链接 认证需要的视图 包含了应用的基础布局文件 ...
- Laravel - 安装与配置
有多重途径可以安装Laravel,下面是通过composer安装laravel的方法.Composer 是 PHP 的一个依赖管理工具.它允许你申明项目所依赖的代码库,它会在你的项目中为你安装他们.c ...
随机推荐
- NetMQ(ZeroMQ)Client => Server => Client 模式的实现
ØMQ (也拼写作ZeroMQ,0MQ或ZMQ)是一个为可伸缩的分布式或并发应用程序设计的高性能异步消息库.它提供一个消息队列, 但是与面向消息的中间件不同,ZeroMQ的运行不需要专门的消息代理(m ...
- JEditorPane中html文档中文乱码解决
Culturally dependent information in some documents is handled through a mechanism called character e ...
- 第六篇、git常用的命令
1.oscine git服务器地址 https://git.oschina.net/ 2.帐号:18775134221@163.com 密码:562011 3.创建私有的仓库 4.使用命令 4.1 配 ...
- table表格中加入<a>标签,使内容上下居中的方法。
主要思路:定义好表格单元格的width和height,再加入<a>后,设置<a>的width=100%,height=100%填充整个单元格.那么此时设置上下左右居中样式就只需 ...
- SSH连接时出现「WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!」解决办法
用ssh來操控github,沒想到連線時,出現「WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!」,後面還有一大串英文,這時當然要向Google大神求助 ...
- JavaScript中,按值传递与按地址(引用)传递。
JavaScript中,数字型,字符串,布尔型等基本类型,传递给变量时,传递方式为按值传递,这个很好理解,不做多解释. 而令人有所疑惑的,是数组,对象等引用类型传递给变量是,传递方式为按地址传递.此处 ...
- android 权限总结
1.拨打电话要权限 2.sd目录存东西要权限
- 程序员面试题精选100题(16)-O(logn)求Fibonacci数列[算法]
作者:何海涛 出处:http://zhedahht.blog.163.com/ 题目:定义Fibonacci数列如下: / 0 n=0 f(n)= ...
- 第33条:用EnumMap代替序数索引
有时候,会见到利用ordinal方法来索引数组的代码.例如下面这个简化的类,表示一种烹饪用的香草: public class Herb { public enum Type { ANNUAL, PER ...
- linux (centos 6.4)安装自定义分区方案(转载)
在计算机上安装 Linux 系统,对硬盘进行分区是一个非常重要的步骤,下面介绍几个分区方案. 方案 1 / :建议大小在 5GB 以上. swap :即交换分区,建议大小是物理内存的 1~2 倍. 方 ...