artisan
// displays help for a given command php artisan --help or -h
// do not output any message php artisan --quiet or -q
// display this application version php artisan --version or -v
// do not ask any interactive question php artisan --no-interaction or -n
// force ansi output php artisan --ansi
// disable ansi output php artisan --no-ansi
// the environment the command should run under php artisan --env
// -v|vv|vvv increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug php artisan --verbose
// display the framework change list php artisan changes // remove the compiled class file php artisan clear-compiled
// put the application into maintenance mode php artisan down // regenerate framework autoload files php artisan dump-autoload
// display the current framework environment php artisan env // displays help for a command php artisan help // lists commands php artisan list // optimize the framework for better performance php artisan optimize // list all registered routes php artisan routes // serve the application on the php development server php artisan serve // change the default port php artisan serve --port 8080
// get it to work outside localhost php artisan serve --host 0.0.0.0
// interact with your application php artisan tinker // bring the application out of maintenance mode php artisan up // create a new package workbench php artisan workbench // publish a package's assets to the public directory php artisan asset:publish [--bench[=vendor/package]] [--path[=...]] [package]
// create a migration for the password reminders table php artisan auth:reminders-table
// flush the application cache php artisan cache:clear
// create a new artisan command (l3:task) php artisan command:make name [--command[=...]] [--path[=...]] [--namespace[=...]]
// publish a package's configuration to the application php artisan config:publish
// create a new resourceful controller php artisan controller:make [--bench=vendor/package]
// seed the database with records php artisan db:seed [--class[=...]] [--database[=...]]
// set the application key php artisan key:generate
// database migrations php artisan migrate [--bench=vendor/package] [--database[=...]] [--path[=...]] [--package[=...]] [--pretend] [--seed]
// create the migration repository php artisan migrate:install [--database[=...]]
// create a new migration file php artisan migrate:make name [--bench=vendor/package] [--create] [--package[=...]] [--path[=...]] [--table[=...]]
// reset and re-run all migrations php artisan migrate:refresh [--database[=...]] [--seed]
// rollback all database migrations php artisan migrate:reset [--database[=...]] [--pretend]
// rollback the last database migration php artisan migrate:rollback [--database[=...]] [--pretend]
// publish a package's migrations to migration directory php artisan migrate:publish vendor/package
// listen to a given queue php artisan queue:listen [--queue[=...]] [--delay[=...]] [--memory[=...]] [--timeout[=...]] [connection]
// subscribe a url to an iron.io push queue php artisan queue:subscribe [--type[=...]] queue url
// process the next job on a queue php artisan queue:work [--queue[=...]] [--delay[=...]] [--memory[=...]] [--sleep] [connection]
// create a migration for the session database table php artisan session:table
// publish a package's views to the application php artisan view:publish [--path[=...]] package
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
configuration
config::get('app.timezone');
//get with default value config::get('app.timezone', 'utc');
//set configuration config::set('database.default', 'sqlite');
routing
route::get('foo', function(){});
route::get('foo', 'controllername@function ');
route::controller('foo', 'foocontroller');
restful controllers
route::resource('posts','postscontroller');
//specify a subset of actions to handle on the route route::resource('photo', 'photocontroller',['only' => ['index', 'show']]);
route::resource('photo', 'photocontroller',['except' => ['update', 'destroy']]);
triggering errors
app::abort(404);
app::missing(function($exception){});
throw new notfoundhttpexception;
route parameters
route::get('foo/{bar}', function($bar){});
route::get('foo/{bar?}', function($bar = 'bar'){});
http verbs
route::any('foo', function(){});
route::post('foo', function(){});
route::put('foo', function(){});
route::patch('foo', function(){});
route::delete('foo', function(){});
// restful actions route::resource('foo', 'foocontroller');
secure routes
route::get('foo', array('https', function(){}));
route constraints
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]'))
// set a pattern to be used across routes route::pattern('bar', '[0-9]+')
filters
// declare an auth filter route::filter('auth', function(){});
// register a class as a filter route::filter('foo', 'foofilter');
route::get('foo', array('before' => 'auth', function(){}));
// routes in this group are guarded by the 'auth' filter route::get('foo', array('before' => 'auth', function(){}));
route::group(array('before' => 'auth'), function(){});
// pattern filter route::when('foo/*', 'foo');
// http verb pattern route::when('foo/*', 'foo', array('post'));
named routes
route::currentroutename();
route::get('foo/bar', array('as' => 'foobar', function(){}));
route prefixing
// this route group will carry the prefix 'foo' route::group(array('prefix' => 'foo'), function(){})
route namespacing
// this route group will carry the namespace 'foo\bar' route::group(array('namespace' => 'foo\bar'), function(){})
sub-domain routing
// {sub} will be passed to the closure route::group(array('domain' => '{sub}.example.com'), function(){});
app
app::environment();
// test equal to app::environment('local');
app::runninginconsole();
app::runningunittests();
log
log::info('info');
log::info('info',array('context'=>'additional info'));
log::error('error');
log::warning('warning');
// get monolog instance log::getmonolog();
// add listener log::listen(function($level, $message, $context) {});
// get all ran queries. db::getquerylog();
urls
url::full();
url::current();
url::previous();
url::to('foo/bar', $parameters, $secure);
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);
url::getgenerator();
url::setgenerator($generator);
events
event::fire('foo.bar', array($bar));
event::listen('foo.bar', 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::queue('foo', array($bar));
event::flusher('foo', function($bar){});
event::flush('foo');
event::forget('foo');
event::subscribe(new fooeventhandler);
database
db::connection('connection_name');
db::statement('drop table users');
db::listen(function($sql, $bindings, $time){ code_here; });
db::transaction(function(){ transaction_code_here; });
// cache a query for $time minutes db::table('users')->remember($time)->get();
// escape raw input db::raw('sql expression here');
selects
db::table('name')->get();
db::table('name')->distinct()->get();
db::table('name')->select('column as column_alias')->get();
db::table('name')->where('name', '=', 'john')->get();
db::table('name')->wherebetween('column', array(1, 100))->get();
db::table('name')->wherein('column', array(1, 2, 3))->get();
db::table('name')->wherenotin('column', array(1, 2, 3))->get();
db::table('name')->wherenull('column')->get();
db::table('name')->wherenotnull('column')->get();
db::table('name')->groupby('column')->get();
// default eloquent sort is ascendant db::table('name')->orderby('column')->get();
db::table('name')->orderby('column','desc')->get();
db::table('name')->having('count', '>', 100)->get();
db::table('name')->skip(10)->take(5)->get();
db::table('name')->first();
db::table('name')->pluck('column');
db::table('name')->lists('column');
// joins db::table('name')->join('table', 'name.id', '=', 'table.id')
->select('name.id', 'table.email');
inserts, updates, deletes
db::table('name')->insert(array('name' => 'john', 'email' => 'john@example.com'));
db::table('name')->insertgetid(array('name' => 'john', 'email' => 'john@example.com'));
// batch insert db::table('name')->insert(array(
array('name' => 'john', 'email' => 'john@example.com'),
array('name' => 'james', 'email' => 'james@example.com')
));
// update an entry db::table('name')->where('name', '=', 'john')
->update(array('email' => 'john@example2.com'));
// delete everything from a table db::table('name')->delete();
// delete specific records db::table('name')->where('id', '>', '10')->delete();
db::table('name')->truncate();
aggregates
db::table('name')->count();
db::table('name')->max('column');
db::table('name')->min('column');
db::table('name')->avg('column');
db::table('name')->sum('column');
db::table('name')->increment('column');
db::table('name')->increment('column', $amount);
db::table('name')->decrement('column');
db::table('name')->decrement('column', $amount);
db::table('name')->remember(5)->get();
db::table('name')->remember(5, 'cache-key-name')->get();
db::table('name')->cachetags('my-key')->remember(5)->get();
db::table('name')->cachetags(array('my-first-key','my-second-key'))->remember(5)->get();
raw expressions
// return rows db::select('select * from users where id = ?', array('value'));
// return nr affected rows db::insert('insert into foo set bar=2');
db::update('update foo set bar=2');
db::delete('delete from bar');
// returns void db::statement('update foo set bar=2');
// raw expression inside a statement db::table('name')->select(db::raw('count(*) as count, column2'))->get();
eloquent
model::create(array('key' => 'value'));
// find first matching record by attributes or create model::firstorcreate(array('key' => 'value'));
// find first record by attributes or instantiate model::firstornew(array('key' => 'value'));
// create or update a record matching attibutes, and fill with values model::updateorcreate(array('search_key' => 'search_value'), array('key' => 'value'));
// fill a model with an array of attributes, beware of mass assignment! model::fill($attributes);
model::destroy(1);
model::all();
model::find(1);
// find using dual primary key model::find(array('first', 'last'));
// throw an exception if the lookup fails model::findorfail(1);
// find using dual primary key and throw exception if the lookup fails model::findorfail(array('first', 'last'));
model::where('foo', '=', 'bar')->get();
model::where('foo', '=', 'bar')->first();
// dynamic model::wherefoo('bar')->first();
// throw an exception if the lookup fails model::where('foo', '=', 'bar')->firstorfail();
model::where('foo', '=', 'bar')->count();
model::where('foo', '=', 'bar')->delete();
//output raw query model::where('foo', '=', 'bar')->tosql();
model::whereraw('foo = bar and cars = 2', array(20))->get();
model::remember(5)->get();
model::remember(5, 'cache-key-name')->get();
model::cachetags('my-tag')->remember(5)->get();
model::cachetags(array('my-first-key','my-second-key'))->remember(5)->get();
model::on('connection-name')->find(1);
model::with('relation')->get();
model::all()->take(10);
model::all()->skip(10);
// default eloquent sort is ascendant model::all()->orderby('column');
model::all()->orderby('column','desc');
soft delete
model::withtrashed()->where('cars', 2)->get();
// include the soft deleted models in the results model::withtrashed()->where('cars', 2)->restore();
model::where('cars', 2)->forcedelete();
// force the result set to only included soft deletes model::onlytrashed()->where('cars', 2)->get();
events
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 configuration
// disables mass assignment exceptions from being thrown from model inserts and updates eloquent::unguard();
// renables any ability to throw mass assignment exceptions eloquent::reguard();
pagination
// auto-magic pagination model::paginate(15);
model::where('cars', 2)->paginate(15);
// next and previous only model::where('cars', 2)->simplepaginate(15);
// manual paginator paginator::make($items, $totalitems, $perpage);
// print page navigators in view $variable->links();
schema
// indicate that the table needs to be created schema::create('table', function($table)
{
$table->increments('id');
});
// specify a connection schema::connection('foo')->create('table', function($table){});
// rename the table to a given name schema::rename($from, $to);
// indicate that the table should be dropped schema::drop('table');
// indicate that the table should be dropped if it exists schema::dropifexists('table');
// determine if the given table exists schema::hastable('table');
// determine if the given table has a given column schema::hascolumn('table', 'column');
// update an existing table schema::table('table', function($table){});
// indicate that the given columns should be renamed $table->renamecolumn('from', 'to');
// indicate that the given columns should be dropped $table->dropcolumn(string|array);
// the storage engine that should be used for the table $table->engine = 'innodb';
// only work on mysql $table->string('name')->after('email');
indexes
$table->string('column')->unique();
$table->primary('column');
// creates a dual primary key $table->primary(array('first', 'last'));
$table->unique('column');
$table->unique('column', 'key_name');
// creates a dual unique index $table->unique(array('first', 'last'));
$table->unique(array('first', 'last'), 'key_name');
$table->index('column');
$table->index('column', 'key_name');
// creates a dual index $table->index(array('first', 'last'));
$table->index(array('first', 'last'), 'key_name');
$table->dropprimary('table_column_primary');
$table->dropunique('table_column_unique');
$table->dropindex('table_column_index');
foreign keys
$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('posts_user_id_foreign');
column types
// increments $table->increments('id');
$table->bigincrements('id');
// numbers $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);
//string and text $table->char('name', 4);
$table->string('email');
$table->string('name', 100);
$table->text('description');
$table->mediumtext('description');
$table->longtext('description');
//date and time $table->date('created_at');
$table->datetime('created_at');
$table->time('sunrise');
$table->timestamp('added_on');
$table->timestamps();
// adds created_at and updated_at columns $table->nullabletimestamps();
// others $table->binary('data');
$table->boolean('confirmed');
$table->softdeletes();
// adds deleted_at column for soft deletes $table->enum('choices', array('foo', 'bar'));
$table->remembertoken();
// adds remember_token as varchar(100) null $table->morphs('parent');
// adds integer parent_id and string parent_type ->nullable()
->default($value)
->unsigned()
input
input::get('key');
// default if the key is missing input::get('key', 'default');
input::has('key');
input::all();
// only retrieve 'foo' and 'bar' when getting input input::only('foo', 'bar');
// disregard 'foo' when getting input input::except('foo');
input::flush();
session input (flash)
// flash input to the session input::flash();
// flash only some of the input to the session input::flashonly('foo', 'bar');
// flash only some of the input to the session input::flashexcept('foo', 'baz');
// retrieve an old input item input::old('key','default_value');
files
// use a file that's been uploaded input::file('filename');
// determine if a file was uploaded input::hasfile('filename');
// access file properties input::file('name')->getrealpath();
input::file('name')->getclientoriginalname();
input::file('name')->getclientoriginalextension();
input::file('name')->getsize();
input::file('name')->getmimetype();
// move an uploaded file input::file('name')->move($destinationpath);
// move an uploaded file 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();
cookies
cookie::get('key');
cookie::get('key', 'default');
// create a cookie that lasts for ever cookie::forever('key', 'value');
// create a cookie that lasts n minutes cookie::make('key', 'value', 'minutes');
// set a cookie before a response has been created cookie::queue('key', 'value', 'minutes');
// forget cookie cookie::forget('key');
// send a cookie with a response $response = response::make('hello world');
// add a cookie to the response $response->withcookie(cookie::make('name', 'value', $minutes));
sessions
session::get('key');
// returns an item from the session session::get('key', 'default');
session::get('key', function(){ return 'default'; });
// get the session id session::getid();
// put a key / value pair in the session session::put('key', 'value');
// push a value into an array in the session session::push('foo.bar','value');
// returns all items from the session session::all();
// checks if an item is defined session::has('key');
// remove an item from the session session::forget('key');
// remove all of the items from the session session::flush();
// generate a new session identifier session::regenerate();
// flash a key / value pair to the session session::flash('key', 'value');
// reflash all of the session flash data session::reflash();
// reflash a subset of the current flash data session::keep(array('key1', 'key2'));
requests
// url: http://xx.com/aa/bb request::url();
// path: /aa/bb request::path();
// getrequesturi: /aa/bb/?c=d request::getrequesturi();
// returns user's ip request::getclientip();
// geturi: http://xx.com/aa/bb/?c=d request::geturi();
// getquerystring: c=d request::getquerystring();
// get the port scheme of the request (e.g., 80, 443, etc.) request::getport();
// determine if the current request uri matches a pattern request::is('foo/*');
// get a segment from the uri (1 based index) request::segment(1);
// retrieve a header from the request request::header('content-type');
// retrieve a server variable from the request request::server('path_info');
// determine if the request is the result of an ajax call request::ajax();
// determine if the request is over https request::secure();
// get the request method request::method();
// checks if the request method is of specified type request::ismethod('post');
// get raw post data request::instance()->getcontent();
// get requested response format request::format();
// true if http content-type header contains */json request::isjson();
// true if http accept header is application/json request::wantsjson();
responses
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);
// create a response and modify a header value $response = response::make($contents, 200);
$response->header('content-type', 'application/json');
return $response;
// attach a cookie to a response return response::make($content)
->withcookie(cookie::make('key', 'value'));
redirects
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);
// create a new redirect response to the previous location return redirect::back();
// create a new redirect response to a named route return redirect::route('foobar');
return redirect::route('foobar', array('value'));
return redirect::route('foobar', array('key' => 'value'));
// create a new redirect response to a controller action return redirect::action('foocontroller@index');
return redirect::action('foocontroller@baz', array('value'));
return redirect::action('foocontroller@baz', array('key' => 'value'));
// if intended redirect is not defined, defaults to foo/bar. return redirect::intended('foo/bar');
ioc
app::bind('foo', function($app){ return new foo; });
app::make('foo');
// if this class exists, it's returned app::make('foobar');
// register a shared binding in the container app::singleton('foo', function(){ return new foo; });
// register an existing instance as shared in the container app::instance('foo', new foo);
// register a binding with the container app::bind('foorepositoryinterface', 'barrepository');
// register a service provider with the application app::register('fooserviceprovider');
// listen for object resolution app::resolving(function($object){});
security
passwords
hash::make('secretpassword');
hash::check('secretpassword', $hashedpassword);
hash::needsrehash($hashedpassword);
auth
// determine if the current user is authenticated auth::check();
// get the currently authenticated user auth::user();
// get the id of the currently authenticated user auth::id();
// attempt to authenticate a user using the given credentials auth::attempt(array('email' => $email, 'password' => $password));
// 'remember me' by passing true to auth::attempt() auth::attempt($credentials, true);
// log in for a single request auth::once($credentials);
// log a user into the application auth::login(user::find(1));
// log the given user id into the application auth::loginusingid(1);
// log the user out of the application auth::logout();
// validate a user's credentials auth::validate($credentials);
// attempt to authenticate using http basic auth auth::basic('username');
// perform a stateless http basic login attempt auth::oncebasic();
// send a password reminder to a user password::remind($credentials, function($message, $user){});
encryption
crypt::encrypt('secretstring');
crypt::decrypt($encryptedstring);
crypt::setmode('ctr');
crypt::setcipher($cipher);
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){});
// write all email to logs instead of sending mail::pretend();
messages
// these can be used on the $message instance passed into mail::send() or mail::queue() $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);
// this uses in-memory data as attachments $message->attachdata('bar', 'data name', $options);
// embed a file in the message and get the cid $message->embed('foo\bar.txt');
$message->embeddata('foo', 'data name', $options);
// get the underlying swift message instance $message->getswiftmessage();
queues
queue::push('sendmail', array('message' => $message));
queue::push('sendemail@send', array('message' => $message));
queue::push(function($job) use $id {});
// same payload to multiple workers queue::bulk(array('sendemail', 'notifyuser'), $payload);
// starting the queue listener php artisan queue:listen
php artisan queue:listen connection
php artisan queue:listen --timeout=60
// process only the first job on the queue php artisan queue:work
// start a queue worker in daemon mode php artisan queue:work --daemon
// create migration file for failed jobs php artisan queue:failed-table
// listing failed jobs php artisan queue:failed
// delete failed job by id php artisan queue:forget 5
// delete all failed jobs 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
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,...
sometimes|required|field
same:field
size:value
timezone
unique:table,column,except,idcolumn
url
views
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');
// share a value across all views view::share('key', 'value');
// nesting views view::make('foo/bar')->nest('name', 'foo/baz', $data);
// register a view composer view::composer('viewname', function($view){});
//register multiple views to a composer view::composer(array('view1', 'view2'), function($view){});
// register a composer class view::composer('viewname', 'foocomposer');
view::creator('viewname', function($view){});
blade templates
@extends('layout.name')
// begin a section @section('name')
// end a section @stop
// end a section and yield @show
@parent
// show a section in a template @yield('name')
@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 4.2 feature @forelse($users as $user)
@empty
@endforelse
// echo content {{ $var }}
// echo escaped content {{{ $var }}}
{{-- blade comment --}}
// echoing data after checking for existence {{{ $name or 'default' }}}
// displaying raw text with curly braces @{{ this will not be processed by blade }}
forms
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');
// generating a checkbox that is checked form::checkbox('name', 'value', true, array('class' => 'name'));
form::radio('name', 'value');
// generating a radio input that is selected 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 '';
});
form::foofield();
html builder
html::macro('name', function(){});
// convert an html string to entities html::entities($value);
// convert entities to html characters html::decode($value);
// generate a link to a javascript file html::script($url, $attributes);
// generate a link to a css file html::style($url, $attributes);
// generate an html image element html::image($url, $alt, $attributes);
// generate a html link html::link($url, 'title', $attributes, $secure);
// generate a https html link html::securelink($url, 'title', $attributes);
// generate a html link to an asset html::linkasset($url, 'title', $attributes, $secure);
// generate a https html link to an asset html::linksecureasset($url, 'title', $attributes);
// generate a html link to a named route html::linkroute($name, 'title', $parameters, $attributes);
// generate a html link to a controller action html::linkaction($action, 'title', $parameters, $attributes);
// generate a html link to an email address html::mailto($email, 'title', $attributes);
// obfuscate an e-mail address to prevent spam-bots from sniffing it html::email($email);
// generate an ordered list of items html::ol($list, $attributes);
// generate an un-ordered list of items html::ul($list, $attributes);
// create a listing html element html::listing($type, $list, $attributes);
// create the html for a listing element html::listingelement($key, $type, $value);
// create the html for a nested listing attribute html::nestedlisting($key, $type, $value);
// build an html attribute string from an array html::attributes($attributes);
// build a single attribute element html::attributeelement($key, $value);
// obfuscate a string to prevent spam-bots from sniffing it html::obfuscate($value);
strings
// transliterate a utf-8 value to ascii str::ascii($value)
str::camel($value)
str::contains($haystack, $needle)
str::endswith($haystack, $needles)
// cap a string with a single instance of a given value. 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)
// generate a more truly random alpha-numeric string. str::random($length = 16)
// generate a random alpha-numeric string. 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)
// convert a value to studly caps case. str::studly($value)
str::macro($name, $macro)
localization
app::setlocale('en');
lang::get('messages.welcome');
lang::get('messages.welcome', array('foo' => 'bar'));
lang::has('messages.welcome');
lang::choice('messages.apples', 10);
// lang::get alias trans('messages.welcome');
files
file::exists('path');
file::get('path');
file::getremote('path');
// get a file's contents by requiring it file::getrequire('path');
// require the given file once file::requireonce('path');
// write the contents of a file file::put('path', 'contents');
// append to a file file::append('path', 'data');
// delete the file at a given path file::delete('path');
// move a file to a new location file::move('path', 'target');
// copy a file to a new location file::copy('path', 'target');
// extract the file extension from a file path file::extension('path');
// get the file type of a given file file::type('path');
// get the file size of a given file file::size('path');
// get the file's last modification time file::lastmodified('path');
// determine if the given path is a directory file::isdirectory('directory');
// determine if the given path is writable file::iswritable('path');
// determine if the given path is a file file::isfile('file');
// find path names matching a given pattern. file::glob($patterns, $flag);
// get an array of all files in a directory. file::files('directory');
// get all of the files from the given directory (recursive). file::allfiles('directory');
// get all of the directories within a given directory. file::directories('directory');
// create a directory file::makedirectory('path', $mode = 0777, $recursive = false);
// copy a directory from one location to another file::copydirectory('directory', 'destination', $options = null);
// recursively delete a directory file::deletedirectory('directory', $preserve = false);
// empty the specified directory of all files and folders file::cleandirectory('directory');
helpers
arrays
array_add($array, 'key', 'value');
// build a new array using a callback array_build($array, function(){});
// divide an array into two arrays. one with keys and the other with values array_divide($array);
// flatten a multi-dimensional associative array with dots array_dot($array);
// get all of the given array except for a specified array of items array_except($array, array('key'));
// fetch a flattened array of a nested array element array_fetch($array, 'key');
// return the first element in an array passing a given truth test array_first($array, function($key, $value){}, $default);
// strips keys from the array array_flatten($array);
// remove one or many array items from a given array using dot notation array_forget($array, 'foo');
// dot notation array_forget($array, 'foo.bar');
// get an item from an array using dot notation array_get($array, 'foo', 'default');
array_get($array, 'foo.bar', 'default');
// get a subset of the items from the given array array_only($array, array('key'));
// return array of key => values array_pluck($array, 'key');
// return and remove 'key' from array array_pull($array, 'key');
// set an array item to a given value using dot notation array_set($array, 'key', 'value');
// dot notation array_set($array, 'key.subkey', 'value');
array_sort($array, function(){});
// first element of an array head($array);
// last element of an array last($array);
paths
app_path();
// get the path to the public folder public_path();
// app root path base_path();
// get the path to the storage folder storage_path();
strings
// convert a value to camel case camel_case($value);
// get the class basename of the given object / class class_basename($class);
// escape a string e('');
// determine if a given string starts with a given substring starts_with('foo bar.', 'foo');
// determine if a given string ends with a given substring ends_with('foo bar.', 'bar.');
// convert a string to snake case snake_case('foobar');
// determine if a given string contains a given substring str_contains('hello foo bar.', 'foo');
// result: foo/bar/ str_finish('foo/bar', '/');
str_is('foo*', 'foobar');
str_plural('car');
str_random(25);
str_limit($value, $limit = 100, $end = '...')
str_singular('cars');
// result: foobar studly_case('foo_bar');
trans('foo.bar');
trans_choice('foo.bar', $count);
urls and links
action('foocontroller@method', $parameters);
link_to('foo/bar', $title, $attributes, $secure);
link_to_asset('img/foo.jpg', $title, $attributes, $secure);
link_to_route('route.name', $title, $parameters, $attributes);
link_to_action('foocontroller@method', $title, $params, $attrs);
// html link asset('img/photo.jpg', $title, $attributes);
// https link secure_asset('img/photo.jpg', $title, $attributes);
secure_url('path', $parameters);
route($route, $parameters, $absolute = true);
url('path', $parameters = array(), $secure = null);
miscellaneous
csrf_token();
dd($value);
value(function(){ return 'bar'; });
with(new foo)->chainedmethod();
unit testing
install and run
// add to composer and update: phpunit/phpunit: 4.0.*
// run tests (from project root) ./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();
// asserting the session has errors for a given key... $this->assertsessionhaserrors('name');
// asserting the session has errors for several keys... $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); // specify remote, otherwise assumes default
ssh::run(array $commands, function($line)
{
echo $line.php_eol;
});
tasks
ssh::define($taskname, array $commands); // define
ssh::task($taskname, function($line) // execute {
echo $line.php_eol;
});
sftp uploads
ssh::put($localfile, $remotepath);
ssh::putstring($string, $remotepath);
filesystem/cloud storage
storage::disk('s3');
storage::disk('local')->put('file.txt', 'contents');
storage::disk('local')->get('file.jpg');
storage::disk('s3')->exists('file.jpg');
storage::get('file.jpg');
storage::put('file.jpg', $contents);
storage::size('file1.jpg');
storage::lastmodified('file1.jpg');
storage::copy('old/file1.jpg', 'new/file1.jpg');
storage::move('old/file1.jpg', 'new/file1.jpg');
storage::prepend('file.log', 'prepended text');
storage::append('file.log', 'appended text');
storage::delete(['file1.jpg', 'file2.jpg']);
storage::files($directory);
storage::allfiles($directory);
storage::directories($directory);
storage::alldirectories($directory);
storage::makedirectory($directory);
storage::deletedirectory($directory);
