安装
composer global require "laravel/installer"
Laravel 可执行文件位于$HOME/.composer/vendor/bin
使用laravel new
创建新项目
laravel new blog
配置
目录权限
Directories within the storage
and the bootstrap/cache
directories should be writable by your web server or Laravel will not run.
Application Key
在.env
配置文件中设置 Application Key,它应该有32 个字符长。
使用
php artisan key:generate
生成一个key。
美化链接
Laravel自带.htaccess
文件,需要开启Apache的mod_rewrite
模块
– nginx配置
location / { try_files $uri $uri/ /index.php?$query_string; }
概念
Service Provider
喵喵喵喵喵?
Service Container
喵喵喵喵喵?
Contracts
Laravel 的 Contracts 是一组定义了框架核心服务的接口( interfaces )。例如,Queue
contract 定义了队列任务所需要的方法,而 Mailer
contract 定义了发送 e-mail 需要的方法。
Facades
喵喵喵喵喵?
路由
路由配置文件位于routes
目录,routes/web.php
与web
中间件组关联;routes/api.php
与api
中间件组关联。
Route::get('foo', function () { return 'Hello World'; });
指向控制器的路由
Route::get('/home', 'HomeController@index'); Route::get('user/{id}', 'UserController@showProfile');
对特定的HTTP请求注册路由
Route::get($uri, $callback); Route::post($uri, $callback); Route::put($uri, $callback); Route::patch($uri, $callback); Route::delete($uri, $callback); Route::options($uri, $callback);
或者也可以直接写成
Route::any($uri, $callback);
参数
示例为必填参数,如果{id}改为{id?}则为可选参数。
Route::get('user/{id}', function ($id) { return 'User '.$id; });
控制器
Controllers can group related HTTP request handling logic into a class. Controllers are typically stored in the app/Http/Controllers
directory.
User::findOrFail($id)]); } }
访问HTTP请求
To obtain an instance of the current HTTP request via dependency injection, you should type-hint the Illuminate\Http\Request class on your controller method. The incoming request instance will automatically be injected by the service container:
input('name'); // } }
视图
Blade 视图文件使用 .blade.php
文件扩展名,并且一般被存放在 resources/views
目录。, we may return it using the global view helper like so:
Route::get('/', function () { return view('greeting', ['name' => 'James']); });
Blade 模板引擎
使用Blade模板定义一个页面布局
@section
指令正像其名字所暗示的一样用来定义一个视图片断(section)。@yield
指令用来展示某个指定 section 所代表的内容。
定义子页面时,使用 @extends
指令来为子页面指定其所“继承”的页面布局模板。
展示变量及函数返回值
Hello, {{ $name }}.
当然,你不仅仅被局限于展示传递给视图的变量,你还可以展示 PHP 函数的返回值。事实上,你可以在 Blade 模板的双花括号表达式中调用任何 PHP 代码:
The current UNIX timestamp is {{ time() }}.
@include
指令允许你方便地在一个视图中引入另一个视图。所有父视图中可用的变量也都可以在被引入的子视图中使用。
控制结构
- 通过
@if
、@elseif
、@else
和@endif
指令可以创建 if 表达式。 - Blade 还提供了简单的循环指令,与 PHP 所支持的循环结构相一致。
静态文件
laravel服务根目录是public
,所以你要把css文件放到public/css
中,然后再用{{asset('路径')}}
。
数据库
运行SQL查询
$results = DB::select('select * from users where id = :id', ['id' => 1]);
数据库迁移
生成一个新迁移
php artisan make:migration create_users_table
迁移内容
一个迁移形如:
increments('id'); $table->string('name'); $table->string('airline'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('flights'); } }
迁移的具体格式见官方文档
https://laravel.com/docs/5.1/migrations#writing-migrations
运行迁移
php artisan migrate
Query Build
Retrieving Results
$user = DB::table('users')->where('name', 'John')->first(); $email = DB::table('users')->where('name', 'John')->value('email');
Aggregates
The query builder also provides a variety of aggregate methods, such as count
, max
, min
, avg
, and sum
. You may call any of these methods after constructing your query:
$users = DB::table('users')->count(); $price = DB::table('orders')->max('price');
Select
Of course, you may not always want to select all columns from a database table. Using the select method, you can specify a custom select clause for the query:
$users = DB::table('users')->select('name', 'email as user_email')->get();
Inserts
The query builder also provides an insert method for inserting records into the database table. The insert method accepts an array of column names and values
You may even insert several records into the table with a single call to insert by passing an array of arrays. Each array represents a row to be inserted into the table:
DB::table('users')->insert([ ['email' => '[email protected]', 'votes' => 0], ['email' => '[email protected]', 'votes' => 0] ]);
Updates
Of course, in addition to inserting records into the database, the query builder can also update existing records using the update method. The update method, like the insert method, accepts an array of column and value pairs containing the columns to be updated. You may constrain the update query using where clauses:
DB::table('users') ->where('id', 1) ->update(['votes' => 1]);
Eloquent
Think of each Eloquent model as a powerful query builder allowing you to fluently query the database table associated with the model.
Since Eloquent models are query builders, you should review all of the methods available on the query builder. You may use any of these methods in your Eloquent queries.
定义一个Eloquent类
To get started, let’s create an Eloquent model. Models typically live in the app
directory。
使用artisan
命令创建一个模型,同时创建一个数据库迁移。
php artisan make:model User -m
执行数据库迁移
php artisan migrate
从表中获取数据
获取整个表:
public function index() { $flights = Flight::all(); return view('flight.index', ['flights' => $flights]); }
遍历返回的model:
foreach ($flights as $flight) { echo $flight->name; }
获取特定的行
// Retrieve a model by its primary key... $flight = App\Flight::find(1); // Retrieve the first model matching the query constraints... $flight = App\Flight::where('active', 1)->first();
异常处理,当返回值为空时将抛出一个Illuminate\Database\Eloquent\ModelNotFoundException
异常。
$model = App\Flight::findOrFail(1);
INSERT和UPDATE
To create a new record in the database, simply create a new model instance, set attributes on the model, then call the `save` method: name = $request->name; $flight->save(); } }
The save
method may also be used to update models that already exist in the database. To update a model, you should retrieve it, set any attributes you wish to update, and then call the save
method. Again, the updated_at
timestamp will automatically be updated, so there is no need to manually set its value:
$flight = App\Flight::find(1); $flight->name = 'New Flight Name'; $flight->save();
App\Flight::where('active', 1) ->where('destination', 'San Diego') ->update(['delayed' => 1]);
认证
Laravel ships with several pre-built authentication controllers, which are located in the App\Http\Controllers\Auth namespace
.
The RegisterController
handles new user registration
the LoginController
handles authentication
the ForgotPasswordController
handles e-mailing links for resetting passwords
the ResetPasswordController
contains the logic to reset passwords.
Each of these controllers uses a trait to include their necessary methods. For many applications, you will not need to modify these controllers at all.
路由
使用命令
php artisan make:auth
快速生成认证所需的路由和视图。
A HomeController
will also be generated to handle post-login requests to your application’s dashboard.
在此之前需要进行数据库迁移来创建数据表和字段。
php artisan migrate
视图
The make:auth
command will also create a resources/views/layouts
directory containing a base layout for your application. All of these views use the Bootstrap CSS framework, but you are free to customize them however you wish.
Validation / Storage Customization
To modify the form fields that are required when a new user registers with your application, or to customize how new users are stored into your database, you may modify the RegisterController
class. This class is responsible for validating and creating new users of your application.
The validator method of the RegisterController contains the validation rules for new users of the application. You are free to modify this method as you wish.
The create method of the RegisterController is responsible for creating new App\User records in your database using the Eloquent ORM. You are free to modify this method according to the needs of your database.
Retrieving The Authenticated User
You may access the authenticated user via the Auth
facade:
use Illuminate\Support\Facades\Auth; $user = Auth::user();
Alternatively, once a user is authenticated, you may access the authenticated user via an Illuminate\Http\Request
instance. Remember, type-hinted classes will automatically be injected into your controller methods: 喵喵喵?
user() returns an instance of the authenticated user... } }
Determining If The Current User Is Authenticated
To determine if the user is already logged into your application, you may use the check method on the Auth
facade, which will return true if the user is authenticated:
use Illuminate\Support\Facades\Auth; if (Auth::check()) { // The user is logged in... }
发表回复/Leave a Reply