Artisan


php artisan make:policy PostPolicy

php artisan --help OR -h

php artisan --quiet OR -q

php artisan --version OR -V

php artisan --no-interaction OR -n

php artisan --ansi

php artisan --no-ansi

php artisan --env

php artisan --verbose

php artisan clear-compiled

php artisan env

php artisan help

php artisan list

php artisan tinker

php artisan down

php artisan up



php artisan optimize [--force] [--psr]

php artisan serve

php artisan serve --port 8080

php artisan serve --host 0.0.0.0

php artisan app:name namespace

php artisan auth:clear-resets

php artisan cache:clear

php artisan cache:table

php artisan config:cache

php artisan config:clear

$exitCode = Artisan::call('config:cache');




php artisan db:seed [--class[="..."]] [--database[="..."]] [--force]


php artisan event:generate



php artisan handler:command [--command="..."] name



php artisan handler:event [--event="..."] [--queued] name


php artisan key:generate



php artisan make:command [--handler] [--queued] name


php artisan make:console [--command[="..."]] name


php artisan make:controller [--plain] name
php artisan make:controller App\\Admin\\Http\\Controllers\\DashboardController

php artisan make:event name

php artisan make:middleware name



php artisan make:migration [--create[="..."]] [--table[="..."]] name

php artisan make:model name

php artisan make:provider name

php artisan make:request name






php artisan migrate [--database[="..."]] [--force] [--path[="..."]] [--pretend] [--seed]

php artisan migrate:install [--database[="..."]]


php artisan migrate:refresh [--database[="..."]] [--force] [--seed] [--seeder[="..."]]

php artisan migrate:reset [--database[="..."]] [--force] [--pretend]

php artisan migrate:rollback [--database[="..."]] [--force] [--pretend]

php artisan migrate:status

php artisan queue:table







php artisan queue:listen [--queue[="..."]] [--delay[="..."]] [--memory[="..."]] [--timeout[="..."]] [--sleep[="..."]] [--tries[="..."]] [connection]

php artisan queue:failed

php artisan queue:failed-table

php artisan queue:flush

php artisan queue:forget

php artisan queue:restart

php artisan queue:retry id




php artisan queue:subscribe [--type[="..."]] queue url








php artisan queue:work [--queue[="..."]] [--daemon] [--delay[="..."]] [--force] [--memory[="..."]] [--sleep[="..."]] [--tries[="..."]] [connection]


php artisan route:cache

php artisan route:clear

php artisan route:list


php artisan schedule:run


php artisan session:table





php artisan vendor:publish [--force] [--provider[="..."]] [--tag[="..."]]
php artisan tail [--path[="..."]] [--lines[="..."]] [connection]
              

Composer

composer create-project laravel/laravel folder_name
composer install
composer update
composer dump-autoload [--optimize]
composer self-update
composer require [options] [--] [vendor/packages]...
              

Config

Config::get('app.timezone');

Config::get('app.timezone', 'UTC');
Config::set('database.default', 'sqlite');
              

Route

Route::get('foo', function(){});
Route::get('foo', 'ControllerName@function');
Route::controller('foo', 'FooController');
              
资源路由
Route::resource('posts','PostsController');

Route::resource('photo', 'PhotoController',['only' => ['index', 'show']]);
Route::resource('photo', 'PhotoController',['except' => ['update', 'destroy']]);
              
触发错误
App::abort(404);
$handler->missing(...) in ErrorServiceProvider::boot();
throw new NotFoundHttpException;
              
路由参数
Route::get('foo/{bar}', function($bar){});
Route::get('foo/{bar?}', function($bar = 'bar'){});
              
HTTP 请求方式
Route::any('foo', function(){});
Route::post('foo', function(){});
Route::put('foo', function(){});
Route::patch('foo', function(){});
Route::delete('foo', function(){});

Route::resource('foo', 'FooController');

Route::match(['get', 'post'], '/', function(){});
              
安全路由 (TBD)
Route::get('foo', array('https', function(){}));
              
路由约束
Route::get('foo/{bar}', function($bar){})
->where('bar', '[0-9]+');
Route::get('foo/{bar}/{baz}', function($bar, $baz){})
->where(array('bar' => '[0-9]+', 'baz' => '[A-Za-z]'))
              

Route::pattern('bar', '[0-9]+')
              
HTTP 中间件

Route::get('admin/profile', ['middleware' => 'auth', function(){}]);
Route::get('admin/profile', function(){})->middleware('auth');
              
命名路由
Route::currentRouteName();
Route::get('foo/bar', array('as' => 'foobar', function(){}));
Route::get('user/profile', [
'as' => 'profile', 'uses' => 'UserController@showProfile'
]);
Route::get('user/profile', 'UserController@showProfile')->name('profile');
$url = route('profile');
$redirect = redirect()->route('profile');
              
路由前缀
Route::group(['prefix' => 'admin'], function()
{
Route::get('users', function(){
return 'Matches The "/admin/users" URL';
});
});
              
路由命名空间

Route::group(array('namespace' => 'Foo\Bar'), function(){})
              
子域名路由

Route::group(array('domain' => '{sub}.example.com'), function(){});
              

Environment

$environment = app()->environment();
$environment = App::environment();
$environment = $app->environment();

if ($app->environment('local')){}

if ($app->environment('local', 'staging')){}
              

Log



Log::info('info');
Log::info('info',array('context'=>'additional info'));
Log::error('error');
Log::warning('warning');

Log::getMonolog();

Log::listen(function($level, $message, $context) {});
              
记录 SQL 查询语句

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

DB::getQueryLog();
              

URL  

URL::full();
URL::current();
URL::previous();
URL::to('foo/bar', $parameters, $secure);
URL::action('NewsController@item', ['id'=>123]);

URL::action('Auth\AuthController@logout');
URL::action('FooController@method', $parameters, $absolute);
URL::route('foo', $parameters, $absolute);
URL::secure('foo/bar', $parameters);
URL::asset('css/foo.css', $secure);
URL::secureAsset('css/foo.css');
URL::isValidUrl('http://example.com');
URL::getRequest();
URL::setRequest($request);
              

Event

Event::fire('foo.bar', array($bar));


Event::listen('App\Events\UserSignup', function($bar){});
Event::listen('foo.*', function($bar){});
Event::listen('foo.bar', 'FooHandler', 10);
Event::listen('foo.bar', 'BarHandler', 5);

Event::listen('foor.bar', function($event){ return false; });
Event::subscribe('UserEventHandler');
              

DB

基本使用
DB::connection('connection_name');

$results = DB::select('select * from users where id = ?', [1]);
$results = DB::select('select * from users where id = :id', ['id' => 1]);

DB::statement('drop table users');

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

DB::transaction(function()
{
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
});
DB::beginTransaction();
DB::rollBack();
DB::commit();
              
查询语句构造器

DB::table('name')->get();

DB::table('users')->chunk(100, function($users)
{
  foreach ($users as $user)
  {
      
  }
});

$user = DB::table('users')->where('name', 'John')->first();
DB::table('name')->first();

$name = DB::table('users')->where('name', 'John')->pluck('name');
DB::table('name')->pluck('column');

$roles = DB::table('roles')->lists('title');
$roles = DB::table('roles')->lists('title', 'name');

$users = DB::table('users')->select('name', 'email')->get();
$users = DB::table('users')->distinct()->get();
$users = DB::table('users')->select('name as user_name')->get();

$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();

$users = DB::table('users')->where('votes', '>', 100)->get();
$users = DB::table('users')
              ->where('votes', '>', 100)
              ->orWhere('name', 'John')
              ->get();
$users = DB::table('users')
      ->whereBetween('votes', [1, 100])->get();
$users = DB::table('users')
      ->whereNotBetween('votes', [1, 100])->get();
$users = DB::table('users')
      ->whereIn('id', [1, 2, 3])->get();
$users = DB::table('users')
      ->whereNotIn('id', [1, 2, 3])->get();
$users = DB::table('users')
      ->whereNull('updated_at')->get();
DB::table('name')->whereNotNull('column')->get();

$admin = DB::table('users')->whereId(1)->first();
$john = DB::table('users')
      ->whereIdAndEmail(2, 'john@doe.com')
      ->first();
$jane = DB::table('users')
      ->whereNameOrAge('Jane', 22)
      ->first();

$users = DB::table('users')
      ->orderBy('name', 'desc')
      ->groupBy('count')
      ->having('count', '>', 100)
      ->get();
DB::table('name')->orderBy('column')->get();
DB::table('name')->orderBy('column','desc')->get();
DB::table('name')->having('count', '>', 100)->get();

$users = DB::table('users')->skip(10)->take(5)->get();
          
Joins

DB::table('users')
    ->join('contacts', 'users.id', '=', 'contacts.user_id')
    ->join('orders', 'users.id', '=', 'orders.user_id')
    ->select('users.id', 'contacts.phone', 'orders.price')
    ->get();

DB::table('users')
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->get();

DB::table('users')
    ->where('name', '=', 'John')
    ->orWhere(function($query)
    {
        $query->where('votes', '>', 100)
              ->where('title', '<>', 'Admin');
    })
    ->get();
          
聚合
$users = DB::table('users')->count();
$price = DB::table('orders')->max('price');
$price = DB::table('orders')->min('price');
$price = DB::table('orders')->avg('price');
$total = DB::table('users')->sum('votes');
          
原始表达句
$users = DB::table('users')
                   ->select(DB::raw('count(*) as user_count, status'))
                   ->where('status', '<>', 1)
                   ->groupBy('status')
                   ->get();

DB::select('select * from users where id = ?', array('value'));
DB::insert('insert into foo set bar=2');
DB::update('update foo set bar=2');
DB::delete('delete from bar');

DB::statement('update foo set bar=2');

DB::table('name')->select(DB::raw('count(*) as count, column2'))->get();
          
Inserts / Updates / Deletes / Unions / Pessimistic Locking

DB::table('users')->insert(
  ['email' => 'john@example.com', 'votes' => 0]
);
$id = DB::table('users')->insertGetId(
  ['email' => 'john@example.com', 'votes' => 0]
);
DB::table('users')->insert([
  ['email' => 'taylor@example.com', 'votes' => 0],
  ['email' => 'dayle@example.com', 'votes' => 0]
]);

DB::table('users')
          ->where('id', 1)
          ->update(['votes' => 1]);
DB::table('users')->increment('votes');
DB::table('users')->increment('votes', 5);
DB::table('users')->decrement('votes');
DB::table('users')->decrement('votes', 5);
DB::table('users')->increment('votes', 1, ['name' => 'John']);

DB::table('users')->where('votes', '<', 100)->delete();
DB::table('users')->delete();
DB::table('users')->truncate();


$first = DB::table('users')->whereNull('first_name');
$users = DB::table('users')->whereNull('last_name')->union($first)->get();

DB::table('users')->where('votes', '>', 100)->sharedLock()->get();
DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();
              

Model

基础使用

class User extends Model {}

php artisan make:model User

class User extends Model {
  protected $table = 'my_users';
}
          
More
Model::create(array('key' => 'value'));

Model::firstOrCreate(array('key' => 'value'));

Model::firstOrNew(array('key' => 'value'));

Model::updateOrCreate(array('search_key' => 'search_value'), array('key' => 'value'));

Model::fill($attributes);
Model::destroy(1);
Model::all();
Model::find(1);

Model::find(array('first', 'last'));

Model::findOrFail(1);

Model::findOrFail(array('first', 'last'));
Model::where('foo', '=', 'bar')->get();
Model::where('foo', '=', 'bar')->first();
Model::where('foo', '=', 'bar')->exists();

Model::whereFoo('bar')->first();

Model::where('foo', '=', 'bar')->firstOrFail();
Model::where('foo', '=', 'bar')->count();
Model::where('foo', '=', 'bar')->delete();

Model::where('foo', '=', 'bar')->toSql();
Model::whereRaw('foo = bar and cars = 2', array(20))->get();
Model::on('connection-name')->find(1);
Model::with('relation')->get();
Model::all()->take(10);
Model::all()->skip(10);

Model::all()->orderBy('column');
Model::all()->orderBy('column','desc');
              
软删除
Model::withTrashed()->where('cars', 2)->get();

Model::withTrashed()->where('cars', 2)->restore();
Model::where('cars', 2)->forceDelete();

Model::onlyTrashed()->where('cars', 2)->get();
              
模型关联

  return $this->hasOne('App\Phone', 'foreign_key', 'local_key');

return $this->belongsTo('App\User', 'foreign_key', 'other_key');


return $this->hasMany('App\Comment', 'foreign_key', 'local_key');

return $this->belongsTo('App\Post', 'foreign_key', 'other_key');


return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'role_id');

return $this->belongsToMany('App\User');

$role->pivot->created_at;

return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');

return $this->belongsToMany('App\Role')->withTimestamps();



return $this->hasManyThrough('App\Post', 'App\User', 'country_id', 'user_id');


return $this->morphTo();

return $this->morphMany('App\Photo', 'imageable');

return $this->morphMany('App\Photo', 'imageable');

Relation::morphMap([
    'Post' => App\Post::class,
    'Comment' => App\Comment::class,
]);



return $this->morphToMany('App\Tag', 'taggable');

return $this->morphToMany('App\Tag', 'taggable');

return $this->morphedByMany('App\Post', 'taggable');

return $this->morphedByMany('App\Video', 'taggable');


$user->posts()->where('active', 1)->get();

$posts = App\Post::has('comments')->get();

$posts = Post::has('comments', '>=', 3)->get();

$posts = Post::has('comments.votes')->get();

$posts = Post::whereHas('comments', function ($query) {
    $query->where('content', 'like', 'foo%');
})->get();


$books = App\Book::with('author')->get();
$books = App\Book::with('author', 'publisher')->get();
$books = App\Book::with('author.contacts')->get();


$books->load('author', 'publisher');


$comment = new App\Comment(['message' => 'A new comment.']);
$post->comments()->save($comment);

$post->comments()->saveMany([
    new App\Comment(['message' => 'A new comment.']),
    new App\Comment(['message' => 'Another comment.']),
]);
$post->comments()->create(['message' => 'A new comment.']);


$user->account()->associate($account);
$user->save();
$user->account()->dissociate();
$user->save();


$user->roles()->attach($roleId);
$user->roles()->attach($roleId, ['expires' => $expires]);

$user->roles()->detach($roleId);

$user->roles()->detach();
$user->roles()->detach([1, 2, 3]);
$user->roles()->attach([1 => ['expires' => $expires], 2, 3]);


$user->roles()->sync([1, 2, 3]);

$user->roles()->sync([1 => ['expires' => true], 2, 3]);

              
事件
Model::creating(function($model){});
Model::created(function($model){});
Model::updating(function($model){});
Model::updated(function($model){});
Model::saving(function($model){});
Model::saved(function($model){});
Model::deleting(function($model){});
Model::deleted(function($model){});
Model::observe(new FooObserver);
              
Eloquent 配置信息

Eloquent::unguard();

Eloquent::reguard();
      

Pagination


Model::paginate(15);
Model::where('cars', 2)->paginate(15);

Model::where('cars', 2)->simplePaginate(15);

Paginator::make($items, $totalItems, $perPage);

$variable->links();
              

Lang

App::setLocale('en');
Lang::get('messages.welcome');
Lang::get('messages.welcome', array('foo' => 'Bar'));
Lang::has('messages.welcome');
Lang::choice('messages.apples', 10);

trans('messages.welcome');
              

File

File::exists('path');
File::get('path');
File::getRemote('path');

File::getRequire('path');

File::requireOnce('path');

File::put('path', 'contents');

File::append('path', 'data');

File::delete('path');

File::move('path', 'target');


File::copy('path', 'target');

File::extension('path');

File::type('path');

File::size('path');

File::lastModified('path');

File::isDirectory('directory');

File::isWritable('path');

File::isFile('file');

File::glob($patterns, $flag);


File::files('directory');

File::allFiles('directory');

File::directories('directory');

File::makeDirectory('path',  $mode = 0777, $recursive = false);

File::copyDirectory('directory', 'destination', $options = null);

File::deleteDirectory('directory', $preserve = false);

File::cleanDirectory('directory');
              

UnitTest

Install and run

composer require "phpunit/phpunit:4.0.*"

./vendor/bin/phpunit
              
Asserts
$this->assertTrue(true);
$this->assertEquals('foo', $bar);
$this->assertCount(1,$times);
$this->assertResponseOk();
$this->assertResponseStatus(403);
$this->assertRedirectedTo('foo');
$this->assertRedirectedToRoute('route.name');
$this->assertRedirectedToAction('Controller@method');
$this->assertViewHas('name');
$this->assertViewHas('age', $value);
$this->assertSessionHasErrors();

$this->assertSessionHasErrors('name');

$this->assertSessionHasErrors(array('name', 'age'));
$this->assertHasOldInput();
              
Calling routes
$response = $this->call($method, $uri, $parameters, $files, $server, $content);
$response = $this->callSecure('GET', 'foo/bar');
$this->session(['foo' => 'bar']);
$this->flushSession();
$this->seed();
$this->seed($connection);
              

SSH

Executing Commands
SSH::run(array $commands);

SSH::into($remote)->run(array $commands);
SSH::run(array $commands, function($line)
{
  echo $line.PHP_EOL;
});
              
任务

SSH::define($taskName, array $commands);

SSH::task($taskName, function($line)
{
  echo $line.PHP_EOL;
});
              
SFTP 上传
SSH::put($localFile, $remotePath);
SSH::putString($string, $remotePath);
              

Schema


Schema::create('table', function($table)
{
  $table->increments('id');
});

Schema::connection('foo')->create('table', function($table){});

Schema::rename($from, $to);

Schema::drop('table');

Schema::dropIfExists('table');

Schema::hasTable('table');

Schema::hasColumn('table', 'column');

Schema::table('table', function($table){});

$table->renameColumn('from', 'to');

$table->dropColumn(string|array);

$table->engine = 'InnoDB';

$table->string('name')->after('email');
              
索引
$table->string('column')->unique();
$table->primary('column');

$table->primary(array('first', 'last'));
$table->unique('column');
$table->unique('column', 'key_name');

$table->unique(array('first', 'last'));
$table->unique(array('first', 'last'), 'key_name');
$table->index('column');
$table->index('column', 'key_name');

$table->index(array('first', 'last'));
$table->index(array('first', 'last'), 'key_name');
$table->dropPrimary(array('column'));
$table->dropPrimary('table_column_primary');
$table->dropUnique(array('column'));
$table->dropUnique('table_column_unique');
$table->dropIndex(array('column'));
$table->dropIndex('table_column_index');
              
外键
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'|'restrict'|'set null'|'no action');
$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade'|'restrict'|'set null'|'no action');
$table->dropForeign(array('user_id'));
$table->dropForeign('posts_user_id_foreign');
              
字段类型

$table->increments('id');
$table->bigIncrements('id');


$table->integer('votes');
$table->tinyInteger('votes');
$table->smallInteger('votes');
$table->mediumInteger('votes');
$table->bigInteger('votes');
$table->float('amount');
$table->double('column', 15, 8);
$table->decimal('amount', 5, 2);


$table->char('name', 4);
$table->string('email');
$table->string('name', 100);
$table->text('description');
$table->mediumText('description');
$table->longText('description');


$table->date('created_at');
$table->dateTime('created_at');
$table->time('sunrise');
$table->timestamp('added_on');


$table->timestamps();
$table->nullableTimestamps();


$table->binary('data');
$table->boolean('confirmed');

$table->softDeletes();
$table->enum('choices', array('foo', 'bar'));

$table->rememberToken();

$table->morphs('parent');
->nullable()
->default($value)
->unsigned()
              

Input

Input::get('key');

Input::get('key', 'default');
Input::has('key');
Input::all();

Input::only('foo', 'bar');

Input::except('foo');
Input::flush();
              
会话周期内 Input

Input::flash();

Input::flashOnly('foo', 'bar');

Input::flashExcept('foo', 'baz');

Input::old('key','default_value');
              
Files

Input::file('filename');

Input::hasFile('filename');

Input::file('name')->getRealPath();
Input::file('name')->getClientOriginalName();
Input::file('name')->getClientOriginalExtension();
Input::file('name')->getSize();
Input::file('name')->getMimeType();

Input::file('name')->move($destinationPath);

Input::file('name')->move($destinationPath, $fileName);
              

Cache

Cache::put('key', 'value', $minutes);
Cache::add('key', 'value', $minutes);
Cache::forever('key', 'value');
Cache::remember('key', $minutes, function(){ return 'value' });
Cache::rememberForever('key', function(){ return 'value' });
Cache::forget('key');
Cache::has('key');
Cache::get('key');
Cache::get('key', 'default');
Cache::get('key', function(){ return 'default'; });
Cache::tags('my-tag')->put('key','value', $minutes);
Cache::tags('my-tag')->has('key');
Cache::tags('my-tag')->get('key');
Cache::tags('my-tag')->forget('key');
Cache::tags('my-tag')->flush();
Cache::increment('key');
Cache::increment('key', $amount);
Cache::decrement('key');
Cache::decrement('key', $amount);
Cache::section('group')->put('key', $value);
Cache::section('group')->get('key');
Cache::section('group')->flush();
              

Cookie

Cookie::get('key');
Cookie::get('key', 'default');

Cookie::forever('key', 'value');

Cookie::make('key', 'value', 'minutes');

Cookie::queue('key', 'value', 'minutes');

Cookie::forget('key');

$response = Response::make('Hello World');
$response->withCookie(Cookie::make('name', 'value', $minutes));
              

Session

Session::get('key');

Session::get('key', 'default');
Session::get('key', function(){ return 'default'; });

Session::getId();

Session::put('key', 'value');

Session::push('foo.bar','value');

Session::all();

Session::has('key');

Session::forget('key');

Session::flush();

Session::regenerate();

Session::flash('key', 'value');

Session::reflash();

Session::keep(array('key1', 'key2'));
              

Request


Request::url();

Request::path();

Request::getRequestUri();

Request::ip();

Request::getUri();

Request::getQueryString();

Request::getPort();

Request::is('foo/*');

Request::segment(1);

Request::header('Content-Type');

Request::server('PATH_INFO');

Request::ajax();

Request::secure();

Request::method();

Request::isMethod('post');

Request::instance()->getContent();

Request::format();

Request::isJson();

Request::wantsJson();
              

Response

return Response::make($contents);
return Response::make($contents, 200);
return Response::json(array('key' => 'value'));
return Response::json(array('key' => 'value'))
->setCallback(Input::get('callback'));
return Response::download($filepath);
return Response::download($filepath, $filename, $headers);

$response = Response::make($contents, 200);
$response->header('Content-Type', 'application/json');
return $response;

return Response::make($content)
->withCookie(Cookie::make('key', 'value'));
              

Redirect

return Redirect::to('foo/bar');
return Redirect::to('foo/bar')->with('key', 'value');
return Redirect::to('foo/bar')->withInput(Input::get());
return Redirect::to('foo/bar')->withInput(Input::except('password'));
return Redirect::to('foo/bar')->withErrors($validator);

return Redirect::back();

return Redirect::route('foobar');
return Redirect::route('foobar', array('value'));
return Redirect::route('foobar', array('key' => 'value'));

return Redirect::action('FooController@index');
return Redirect::action('FooController@baz', array('value'));
return Redirect::action('FooController@baz', array('key' => 'value'));

return Redirect::intended('foo/bar');
              

Container

App::bind('foo', function($app){ return new Foo; });
App::make('foo');

App::make('FooBar');

App::singleton('foo', function(){ return new Foo; });

App::instance('foo', new Foo);

App::bind('FooRepositoryInterface', 'BarRepository');

App::register('FooServiceProvider');

App::resolving(function($object){});
              

Security

哈希
Hash::make('secretpassword');
Hash::check('secretpassword', $hashedPassword);
Hash::needsRehash($hashedPassword);
              
加密解密
Crypt::encrypt('secretstring');
Crypt::decrypt($encryptedString);
Crypt::setMode('ctr');
Crypt::setCipher($cipher);
              

Auth

用户认证

Auth::check();

Auth::user();

Auth::id();

Auth::attempt(['email' => $email, 'password' => $password]);

Auth::attempt($credentials, true);

Auth::once($credentials);

Auth::login(User::find(1));

Auth::loginUsingId(1);

Auth::logout();

Auth::validate($credentials);


Auth::basic('username');


Auth::onceBasic();

Password::remind($credentials, function($message, $user){});
              
用户授权

Gate::define('update-post', 'Class@method');
Gate::define('update-post', function ($user, $post) {...});

Gate::define('delete-comment', function ($user, $post, $comment) {});


Gate::denies('update-post', $post);
Gate::allows('update-post', $post);
Gate::check('update-post', $post);

Gate::forUser($user)->allows('update-post', $post);

User::find(1)->can('update-post', $post);
User::find(1)->cannot('update-post', $post);


Gate::before(function ($user, $ability) {});
Gate::after(function ($user, $ability) {});


@can('update-post', $post)
@endcan

@can('update-post', $post)
@else
@endcan


php artisan make:policy PostPolicy

policy($post)->update($user, $post)


$this->authorize('update', $post);

$this->authorizeForUser($user, 'update', $post);

              

Mail

Mail::send('email.view', $data, function($message){});
Mail::send(array('html.view', 'text.view'), $data, $callback);
Mail::queue('email.view', $data, function($message){});
Mail::queueOn('queue-name', 'email.view', $data, $callback);
Mail::later(5, 'email.view', $data, function($message){});

Mail::pretend();
              
消息

$message->from('email@example.com', 'Mr. Example');
$message->sender('email@example.com', 'Mr. Example');
$message->returnPath('email@example.com');
$message->to('email@example.com', 'Mr. Example');
$message->cc('email@example.com', 'Mr. Example');
$message->bcc('email@example.com', 'Mr. Example');
$message->replyTo('email@example.com', 'Mr. Example');
$message->subject('Welcome to the Jungle');
$message->priority(2);
$message->attach('foo\bar.txt', $options);

$message->attachData('bar', 'Data Name', $options);

$message->embed('foo\bar.txt');
$message->embedData('foo', 'Data Name', $options);

$message->getSwiftMessage();
              

Queue

Queue::push('SendMail', array('message' => $message));
Queue::push('SendEmail@send', array('message' => $message));
Queue::push(function($job) use $id {});

Queue::bulk(array('SendEmail', 'NotifyUser'), $payload);

php artisan queue:listen
php artisan queue:listen connection
php artisan queue:listen --timeout=60

php artisan queue:work

php artisan queue:work --daemon

php artisan queue:failed-table

php artisan queue:failed

php artisan queue:forget 5

php artisan queue:flush
              

Validation

Validator::make(
array('key' => 'Foo'),
array('key' => 'required|in:Foo')
);
Validator::extend('foo', function($attribute, $value, $params){});
Validator::extend('foo', 'FooValidator@validate');
Validator::resolver(function($translator, $data, $rules, $msgs)
{
return new FooValidator($translator, $data, $rules, $msgs);
});
              
Rules
accepted
active_url
after:YYYY-MM-DD
before:YYYY-MM-DD
alpha
alpha_dash
alpha_num
array
between:1,10
confirmed
date
date_format:YYYY-MM-DD
different:fieldname
digits:value
digits_between:min,max
boolean
email
exists:table,column
image
in:foo,bar,...
not_in:foo,bar,...
integer
numeric
ip
max:value
min:value
mimes:jpeg,png
regex:[0-9]
required
required_if:field,value
required_with:foo,bar,...
required_with_all:foo,bar,...
required_without:foo,bar,...
required_without_all:foo,bar,...
same:field
size:value
timezone
unique:table,column,except,idColumn
url

              

View

View::make('path/to/view');
View::make('foo/bar')->with('key', 'value');
View::make('foo/bar')->withKey('value');
View::make('foo/bar', array('key' => 'value'));
View::exists('foo/bar');

View::share('key', 'value');

View::make('foo/bar')->nest('name', 'foo/baz', $data);

View::composer('viewname', function($view){});

View::composer(array('view1', 'view2'), function($view){});

View::composer('viewname', 'FooComposer');
View::creator('viewname', function($view){});
              

Blade


@yield('name')

@extends('layout.name')

@section('name')
@stop

@section('sidebar')
@show

@parent

@include('view.name')

@include('view.name', array('key' => 'value'));

@lang('messages.name')
@choice('messages.name', 1);

@if
@else
@elseif
@endif

@unless
@endunless

@for
@endfor

@foreach
@endforeach

@while
@endwhile


@forelse($users as $user)
@empty
@endforelse


{{ $var }}

{!! $var !!}
{{-- Blade 注释,不会被输出到页面中 --}}

{{{ $name or 'Default' }}}

@{{ name }}
              

Form

Form::open(array('url' => 'foo/bar', 'method' => 'PUT'));
Form::open(array('route' => 'foo.bar'));
Form::open(array('route' => array('foo.bar', $parameter)));
Form::open(array('action' => 'FooController@method'));
Form::open(array('action' => array('FooController@method', $parameter)));
Form::open(array('url' => 'foo/bar', 'files' => true));
Form::close();
Form::token();
Form::model($foo, array('route' => array('foo.bar', $foo->bar)));

              
Form Elements
Form::label('id', 'Description');
Form::label('id', 'Description', array('class' => 'foo'));
Form::text('name');
Form::text('name', $value);
Form::text('name', $value, array('class' => 'name'));
Form::textarea('name');
Form::textarea('name', $value);
Form::textarea('name', $value, array('class' => 'name'));
Form::hidden('foo', $value);
Form::password('password');
Form::password('password', array('placeholder' => 'Password'));
Form::email('name', $value, array());
Form::file('name', array('class' => 'name'));
Form::checkbox('name', 'value');

Form::checkbox('name', 'value', true, array('class' => 'name'));
Form::radio('name', 'value');

Form::radio('name', 'value', true, array('class' => 'name'));
Form::select('name', array('key' => 'value'));
Form::select('name', array('key' => 'value'), 'key', array('class' => 'name'));
Form::selectRange('range', 1, 10);
Form::selectYear('year', 2011, 2015);
Form::selectMonth('month');
Form::submit('Submit!', array('class' => 'name'));
Form::button('name', array('class' => 'name'));
Form::macro('fooField', function()
{
return '<input type="custom"/>';
});
Form::fooField();
              

HTML

HTML::macro('name', function(){});

HTML::entities($value);

HTML::decode($value);

HTML::script($url, $attributes);

HTML::style($url, $attributes);

HTML::image($url, $alt, $attributes);

HTML::link($url, 'title', $attributes, $secure);

HTML::secureLink($url, 'title', $attributes);

HTML::linkAsset($url, 'title', $attributes, $secure);

HTML::linkSecureAsset($url, 'title', $attributes);

HTML::linkRoute($name, 'title', $parameters, $attributes);

HTML::linkAction($action, 'title', $parameters, $attributes);

HTML::mailto($email, 'title', $attributes);

HTML::email($email);

HTML::ol($list, $attributes);

HTML::ul($list, $attributes);
HTML::listing($type, $list, $attributes);
HTML::listingElement($key, $type, $value);
HTML::nestedListing($key, $type, $value);

HTML::attributes($attributes);

HTML::attributeElement($key, $value);

HTML::obfuscate($value);
              

String


Str::ascii($value)
Str::camel($value)
Str::contains($haystack, $needle)
Str::endsWith($haystack, $needles)
Str::finish($value, $cap)
Str::is($pattern, $value)
Str::length($value)
Str::limit($value, $limit = 100, $end = '...')
Str::lower($value)
Str::words($value, $words = 100, $end = '...')
Str::plural($value, $count = 2)

Str::random($length = 16)

Str::quickRandom($length = 16)
Str::upper($value)
Str::title($value)
Str::singular($value)
Str::slug($title, $separator = '-')
Str::snake($value, $delimiter = '_')
Str::startsWith($haystack, $needles)
Str::studly($value)
Str::macro($name, $macro)
              

Helper

数组

array_add($array, 'key', 'value');

array_collapse($array);

array_divide($array);

array_dot($array);

array_except($array, array('key'));

array_first($array, function($key, $value){}, $default);


array_flatten(['name' => 'Joe', 'languages' => ['PHP', 'Ruby']]);

array_forget($array, 'foo');
array_forget($array, 'foo.bar');

array_get($array, 'foo', 'default');
array_get($array, 'foo.bar', 'default');

array_has($array, 'products.desk');

array_only($array, array('key'));

array_pluck($array, 'key');

array_pull($array, 'key');

array_set($array, 'key', 'value');
array_set($array, 'key.subkey', 'value');

array_sort($array, function(){});

array_sort_recursive();

array_where();

head($array);

last($array);
              
路径

app_path();

base_path();

config_path();

database_path();

elixir();

public_path();

storage_path();
              
字符串

camel_case($value);

class_basename($class);
class_basename($object);

e('<html>');

starts_with('Foo bar.', 'Foo');

ends_with('Foo bar.', 'bar.');

snake_case('fooBar');

str_limit();

str_contains('Hello foo bar.', 'foo');

str_finish('foo/bar', '/');

str_is('foo*', 'foobar');

str_plural('car');

str_random(25);

str_singular('cars');

str_slug("Laravel 5 Framework", "-");

studly_case('foo_bar');

trans('foo.bar');

trans_choice('foo.bar', $count);
              
URLs and Links

action('FooController@method', $parameters);

asset('img/photo.jpg', $title, $attributes);

secure_asset('img/photo.jpg', $title, $attributes);

route($route, $parameters, $absolute = true);

url('path', $parameters = array(), $secure = null);
              
Miscellaneous

auth()->user();

back();

bcrypt('my-secret-password');

collect(['taylor', 'abigail']);

config('app.timezone', $default);

{!! csrf_field() !!}

$token = csrf_token();

dd($value);

$env = env('APP_ENV');
$env = env('APP_ENV', 'production');

event(new UserRegistered($user));

$user = factory(App\User::class)->make();

{!! method_field('delete') !!}

$value = old('value');
$value = old('value', 'default');

return redirect('/home');

$value = request('key', $default = null)

return response('Hello World', 200, $headers);

$value = session('key');

$value = session()->get('key');
session()->put('key', $value);

value(function(){ return 'bar'; });

return view('auth.login');

$value = with(new Foo)->work();
              

Collection


collect([1, 2, 3]);

$collection->all();

$collection->avg();

$collection->chunk(4);

$collection->collapse();

$collection->contains('New York');

$collection->count();

$collection = $collection->each(function ($item, $key) {
});

$collection->every(4);

$collection->every(4, 1);

$collection->except(['price', 'discount']);

$filtered = $collection->filter(function ($item) {
    return $item > 2;
});

collect([1, 2, 3, 4])->first(function ($key, $value) {
    return $value > 2;
});

$flattened = $collection->flatten();

$flipped = $collection->flip();

$collection->forget('name');

$chunk = $collection->forPage(2, 3);

$value = $collection->get('name');

$grouped = $collection->groupBy('account_id');

$collection->has('email');

$collection->implode('product', ', ');

$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);

collect([])->isEmpty();

$keyed = $collection->keyBy('product_id');

$keyed = $collection->keyBy(function ($item) {
    return strtoupper($item['product_id']);
});

$keys = $collection->keys();

$collection->last();

$multiplied = $collection->map(function ($item, $key) {
    return $item * 2;
});

$max = collect([['foo' => 10], ['foo' => 20]])->max('foo');
$max = collect([1, 2, 3, 4, 5])->max();

$merged = $collection->merge(['price' => 100, 'discount' => false]);

$min = collect([['foo' => 10], ['foo' => 20]])->min('foo');
$min = collect([1, 2, 3, 4, 5])->min();

$filtered = $collection->only(['product_id', 'name']);

$plucked = $collection->pluck('name');

$collection->pop();

$collection->prepend(0);

$collection->prepend(0, 'zero');

$collection->pull('name');

$collection->push(5);

$collection->put('price', 100);

$collection->random();

$random = $collection->random(3);

$total = $collection->reduce(function ($carry, $item) {
    return $carry + $item;
});

$filtered = $collection->reject(function ($item) {
    return $item > 2;
});

$reversed = $collection->reverse();

$collection->search(4);

$collection->shift();

$shuffled = $collection->shuffle();

$slice = $collection->slice(4);

$sorted = $collection->sort();

$sorted = $collection->sortBy('price');

$chunk = $collection->splice(2);

collect([1, 2, 3, 4, 5])->sum();

$chunk = $collection->take(3);

$collection->toArray();

$collection->toJson();

$collection->transform(function ($item, $key) {
    return $item * 2;
});

$unique = $collection->unique();

$values = $collection->values();

$filtered = $collection->where('price', 100);

$zipped = $collection->zip([100, 200]);