composer global require "laravel/installer=~1.1" laravel new ${applicationName}
Artisan
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 php artisan changes php artisan clear-compiled php artisan downgrade php artisan dump-autoload php artisan env php artisan help php artisan list php artisan migrate php artisan optimize php artisan routes php artisan serve php artisan tinker php artisan up php artisan workbench php artisan asset:publish [--bench[="vendor/package"]] [--path[="..."]] [package] php artisan auth:reminders php artisan cache:clear php artisan config:publish php artisan controller:make [--bench="vendor/package"] php artisan db:seed [--class[="..."]] [--database[="..."]] php artisan key:generate php artisan migrate [--bench="vendor/package"] [--database[="..."]] [--path[="..."]] [--package[="..."]] [--pretend] [--seed] php artisan migrate:install [--database[="..."]] php artisan migrate:make name [--bench="vendor/package"] [--create] [--package[="..."]] [--path[="..."]] [--table[="..."]] php artisan migrate:refresh [--database[="..."]] [--seed] php artisan migrate:reset [--database[="..."]] [--pretend] php artisan migrate:rollback [--database[="..."]] [--pretend] php artisan queue:listen [--queue[="..."]] [--delay[="..."]] [--memory[="..."]] [--timeout[="..."]] [connection] php artisan queue:subscribe [--type[="..."]] queue url php artisan queue:work [--queue[="..."]] [--delay[="..."]] [--memory[="..."]] [--sleep] [connection] php artisan session:table php artisan view:publish [--path[="..."]] package php artisan generate:model php artisan generate:controller php artisan generate:view php artisan generate:seed php artisan generate:migration php artisan generate:resource (Generate a model, Generate index, show, create, and edit views, Generate a controller, Generate a migration with schema, Generate a table seeder, Migrate the database) php artisan command:make name [--command[="..."]] [--path[="..."]] [--namespace[="..."]] ./artisan make:command compile // Launch server/project php artisan serve // commands list php artisan list // command help php artisan help migrate // Laravel console php artisan tinker // Route list php artisan route:list Create and update data tables (with migrations) // Create data table php artisan make:migration create_products_table // cache management php artisan cache:clear php artisan config:clear php artisan view:clear // others composer dump-autoload php artisan optimize php artisan route:clear
Composer
composer create-project laravel/laravel folder_name composer install composer update composer dump-autoload [--optimize] composer self-update
Schema management
// Create table(migration exemple)
Schema::create('products', function (Blueprint $table) {
// auto-increment primary key
$table->id();
// created_at and updated_at
$table->timestamps();
// Unique constraint
$table->string('modelNo')->unique();
// Not required
$table->text('description')->nullable();
// Default value
$table->boolean('isActive')->default(true);
// Index
$table->index(['account_id', 'created_at']);
// Foreign Key relation
$table->foreignId('user_id')->constrained('users')->onDelete('cascade');
});
// Update table (migration exemple)
php artisan make:migration add_comment_to_products_table
// up()
Schema::table('users', function (Blueprint $table) {
$table->text('comment');
});
// down()
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('comment');
});
schema commands
Commons commands // Database migration php artisan migrate // Data seed php artisan db:seed // Create table migration php artisan make:migration create_products_table // Create from model with migration, factory, resource controller php artisan make:model Product -all // Create a controller php artisan make:controller ProductsController // Update table migration php artisan make:migration add_date_to_blogposts_table // Rollback latest migration php artisan migrate:rollback // Rollback all migrations php artisan migrate:reset // Rollback all and re-migrate php artisan migrate:refresh // Rollback all, re-migrate and seed php artisan migrate:refresh --seed
Routing
Route::get('foo', function(){});
Route::get('foo', 'ControllerName@function');
Route::controller('foo', 'FooController');
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]'))
Filters
// Declare an auth filter
Route::filter('auth', function(){});
// Register a class as a filter
Route::filter('foo', 'FooFilter');
// 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(){})
Sub-Domain Routing
// {sub} will be passed to the closure
Route::group(array('domain' => '{sub}.example.com'), function(){});
Routes
// Basic route closure
Route::get('/greeting', function () {
return 'Hello World';
});
// Route direct view shortcut
Route::view('/welcome', 'welcome');
// Route to controller class
use App\Http\Controllers\UserController;
Route::get('/user', [UserController::class, 'index']);
// Route only for specific HTTP verbs
Route::match(['get', 'post'], '/', function () {
//
});
// Route for all verbs
Route::any('/', function () {
//
});
// Route Redirect
Route::redirect('/clients', '/customers');
// Route Parameters
Route::get('/user/{id}', function ($id) {
return 'User '.$id;
});
// Optional Parameter
Route::get('/user/{name?}', function ($name = 'John') {
return $name;
});
// Named Route
Route::get(
'/user/profile',
[UserProfileController::class, 'show']
)->name('profile');
// Resource
Route::resource('photos', PhotoController::class);
GET /photos index photos.index
GET /photos/create create photos.create
POST /photos store photos.store
GET /photos/{photo} show photos.show
GET /photos/{photo}/edit edit photos.edit
PUT/PATCH /photos/{photo} update photos.update
DELETE /photos/{photo} destroy photos.destroy
// Nested resource
Route::resource('photos.comments', PhotoCommentController::class);
// Partial resource
Route::resource('photos', PhotoController::class)->only([
'index', 'show'
]);
Route::resource('photos', PhotoController::class)->except([
'create', 'store', 'update', 'destroy'
]);
// URL with route name
$url = route('profile', ['id' => 1]);
// Generating Redirects...
return redirect()->route('profile');
// Route Prefix group
Route::prefix('admin')->group(function () {
Route::get('/users', function () {
// Matches The "/admin/users" URL
});
});
// Route implicit binding
use App\Models\User;
Route::get('/users/{user}', function (User $user) {
return $user->email;
});
// Route fallback
Route::fallback(function () {
//
});
// Route Caching
php artisan route:cache
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::subscribe(new FooEventHandler);
DB
$results = DB::select('select * from users where id = ?', array('value'));
DB::insert('insert into users (id, name) values (?, ?)', array(1, 'Dayle'));
DB::update('update users set votes = 100 where name = ?', array('John'));
DB::delete('delete from users');
DB::statement('drop table users');
DB::listen(function($sql, $bindings, $time){ code_here() });
DB::transaction(function(){ code_here() });
Eloquent
Model::create(array('key' => 'value'));
Model::destroy(1);
Model::all();
Model::find(1);
// Trigger an exception
Model::findOrFail(1);
Model::where('foo', '=', 'bar')->get();
Model::where('foo', '=', 'bar')->first();
// Exception
Model::where('foo', '=', 'bar')->firstOrFail();
Model::where('foo', '=', 'bar')->count();
Model::where('foo', '=', 'bar')->delete();
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);
Database direct access no model
use Illuminate\Support\Facades\DB;
$user = DB::table('users')->first();
$users = DB::select('select name, email from users');
DB::insert('insert into users (name, email, password) value(?, ?, ?)', ['rickavmaniac', 'ericchap@hey.com', 'coeurs40']);
DB::update('update users set name = ? where id = 1', ['eric']);
DB::delete('delete from users where id = 1');
Soft Delete
Model::withTrashed()->where('cars', 2)->get();
Model::withTrashed()->where('cars', 2)->restore();
Model::where('cars', 2)->forceDelete();
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);
Models
// Model mass assignment list exclude attributes
protected $guarded = []; // empty == All
// Or list included attributes
protected $fillable = ['name', 'email', 'password',];
// One to Many relationship (posts with many comments)
public function comments() {
return $this->hasMany(Comment:class);
}
// One to Many relationship (comments with one post)
public function post() {
return $this->belongTo(Post::class);
}
// One to one relationship (Author with one profile)
public function profile() {
return $this->hasOne(Profile::class);
}
// One to one relationship (Profile with one Author)
public function author() {
return $this->belongTo(Author::class);
}
// Many to Many relationship
// 3 tables (posts, tags and post_tag)
// post_tag (post_id, tag_id)
// in Tag model...
public function posts() {
return $this->belongsToMany(Post::class);
}
// in Post model...
public function tags() {
return $this->belongsToMany(Tag::class);
}
// ORM
// New
$flight = new Flight;
$flight->name = $request->name;
$flight->save();
// Update
$flight = Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();
// Create
$user = User::create(['first_name' => 'Taylor','last_name' => 'Otwell']);
// Update All:
Flight::where('active', 1)->update(['delayed' => 1]);
// Delete
$current_user = User::Find(1)
$current_user.delete();
// Delete by id:
User::destroy(1);
// Delete all
$deletedRows = Flight::where('active', 0)->delete();
// Get All
$items = Item::all().
// Find one by primary key
$flight = Flight::find(1);
// display 404 if not found
$model = Flight::findOrFail(1);
// Get last entry
$items = Item::latest()->get()
// Chain
$flights = App\Flight::where('active', 1)->orderBy('name', 'desc')->take(10)->get();
// Where
Todo::where('id', $id)->firstOrFail()
// Like
Todos::where('name', 'like', '%' . $my . '%')->get()
// Or where
Todos::where('name', 'mike')->orWhere('title', '=', 'Admin')->get();
// Count
$count = Flight::where('active', 1)->count();
// Sum
$sum = Flight::where('active', 1)->sum('price');
// Contain?
if ($project->$users->contains('mike'))
Controllers
// Set validation rules
protected $rules = [
'title' => 'required|unique:posts|max:255',
'name' => 'required|min:6',
'email' => 'required|email',
'publish_at' => 'nullable|date',
];
// Validate
$validatedData = $request->validate($rules)
// Show 404 error page
abort(404, 'Sorry, Post not found')
// Controller CRUD exemple
Class ProductsController {
public function index() {
$products = Product::all();
// app/resources/views/products/index.blade.php
return view('products.index', ['products', $products]);
}
public function create() {
return view('products.create');
}
public function store() {
Product::create(request()->validate([
'name' => 'required',
'price' => 'required',
'note' => 'nullable'
]));
return redirect(route('products.index'));
}
//method with model injection
public function show(Product $product) {
return view('products.show', ['product', $product]);
}
public function edit(Product $product) {
return view('products.edit', ['product', $product]);
}
public function update(Product $product) {
Product::update(request()->validate([
'name' => 'required',
'price' => 'required',
'note' => 'nullable'
]));
return redirect(route($product->path()));
}
public function delete(Product $product) {
$product->delete();
return redirect("/contacts");
}
}
// Query Params www.demo.html?name=mike
request()->name //mike
// Form data (or default value)
request()->input('email', 'no@email.com')
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();
Queues
Queue::push('SendMail', array('message' => $message));
Queue::push('SendEmail@send', array('message' => $message));
Queue::push(function($job) use $id {});
php artisan queue:listen
php artisan queue:listen connection
php artisan queue:listen --timeout=60
php artisan queue:work
Localization
App::setLocale('en');
Lang::get('messages.welcome');
Lang::get('messages.welcome', array('foo' => 'Bar'));
Lang::has('messages.welcome');
Lang::choice('messages.apples', 10);
Files
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');
// 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');
File::makeDirectory('path', $mode = 0777, $recursive = false);
File::copyDirectory('directory', 'destination', $options = null);
File::deleteDirectory('directory', $preserve = false);
File::cleanDirectory('directory');
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');
Session Input (flash)
// Flash input to the session
Input::flash();
Input::flashOnly('foo', 'bar');
Input::flashExcept('foo', 'baz');
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')->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::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');
// Create a cookie that lasts for ever
Cookie::forever('key', 'value');
// Send a cookie with a response
$response = Response::make('Hello World');
$response->withCookie(Cookie::make('name', 'value', $minutes));
Sessions
Session::get('key');
Session::get('key', 'default');
Session::get('key', function(){ return 'default'; });
Session::put('key', 'value');
Session::all();
Session::has('key');
Session::forget('key');
Session::flush();
Session::regenerate();
Session::flash('key', 'value');
Session::reflash();
Session::keep(array('key1', 'key2'));
Requests
Request::path();
Request::is('foo/*');
Request::url();
Request::segment(1);
Request::header('Content-Type');
Request::server('PATH_INFO');
Request::ajax();
Request::secure();
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);
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'));
// If intended redirect is not defined, defaults to foo/bar.
return Redirect::intended('foo/bar');
Helpers
// Display variable content and kill execution
dd($products)
// Create a Laravel collection from array.
$collection = collect($array);
// Sort by description ascending
$ordered_collection = $collection->orderBy(‘description’);
// Reset numbering value
$ordered_collection = $ordered_collection->values()->all();
Flash & Session
// Flash (only next request)
$request->session()->flash('status', 'Task was successful!');
// Flash with redirect
return redirect('/home')->with('success' => 'email sent!');
// Set Session
$request->session()->put('key', 'value');
// Get session
$value = session('key');
If session: if ($request->session()->has('users'))
// Delete session
$request->session()->forget('key');
// Display flash in template
@if (session('message')) {{ session('message') }} @endif
HTTP Client
// Use package
use Illuminate\Support\Facades\Http;
//Http get
$response = Http::get('www.thecat.com')
$data = $response->json()
// Http get with query
$res = Http::get('www.thecat.com', ['param1', 'param2'])
// Http post
$res = Http::post('http://test.com', ['name' => 'Steve','role' => 'Admin']);
// Bearer
$res = Http::withToken('123456789')->post('http://the.com', ['name' => 'Steve']);
// Headers
$res = Http::withHeaders(['type'=>'json'])->post('http://the.com', ['name' => 'Steve']);
Storage (helper class to store files locally or in the cloud)
// Make the Public config available from the web
php artisan storage:link
// Public config: Local storage/app/public
Storage::disk('public')->exists('file.jpg'))
// S3 config: storage: Amazon cloud ex:
Storage::disk('s3')->exists('file.jpg'))
// Get or put file in the storage folder
use Illuminate\Support\Facades\Storage;
Storage::disk('public')->put('example.txt', 'Contents');
$contents = Storage::disk('public')->get('file.jpg');
// Access files by generating a url
$url = Storage::url('file.jpg');
// or by direct path to public config
<img src={{ asset('storage/image1.jpg') }}/>
// Delete file
Storage::delete('file.jpg');
// Trigger download
Storage::disk('public')->download('export.csv');
App::bind('foo', function($app){ return new Foo; });
App::make('foo');
// If this class exists, it's returned
App::make('FooBar');
App::singleton('foo', function(){ return new Foo; });
App::instance('foo', new Foo);
App::bind('FooRepositoryInterface', 'BarRepository');
App::register('FooServiceProvider');
// Listen for object resolution
App::resolving(function($object){});
@see app/Providers/AppServiceProvider.php
class AppServiceProvider extends ServiceProvider {
public function register() {
$this->app->singleton(ODBCDatabase::class, function ($app) {
$settings = Config::get('xxx');
return new Kind_of_Database($settings);
});
}
}
Passwords
Hash::make('secretpassword');
Hash::check('secretpassword', $hashedPassword);
Hash::needsRehash($hashedPassword);
Auth
// Check if the user is logged in
Auth::check();
Auth::user();
Auth::attempt(array('email' => $email, 'password' => $password));
// Remember user login
Auth::attempt($credentials, true);
// Log in for a single request
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){});
Encryption
Crypt::encrypt('secretstring');
Crypt::decrypt($encryptedString);
Crypt::setMode('ctr');
Crypt::setCipher($cipher);
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);
});
Validation Rules
accepted active_url after:YYYY-MM-DD before:YYYY-MM-DD alpha alpha_dash alpha_num between:1,10 confirmed date date_format:YYYY-MM-DD different:fieldname email exists:table,column image in:foo,bar,baz not_in:foo,bar,baz integer numeric ip max:value min:value mimes:jpeg,png regex:[0-9] required required_if:field,value required_with:foo,bar,baz required_without:foo,bar,baz same:field size:value unique:table,column,except,idColumn url
Views
View::make('path/to/view');
View::make('foo/bar')->with('key', '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
<!-- Route name -->
<a href="{{ route('routeName.show', $id) }}">
<!-- Template inheritance -->
@yield('content') <!-- layout.blade.php -->
@extends('layout')
@section('content') … @endsection
<!-- Template include -->
@include('view.name', ['name' => 'John'])
<!-- Template variable -->
{{ var_name }}
<!-- raw safe html variable -->
{ !! var_name !! }
<!-- Interation -->
@foreach ($items as $item)
{{ $item.name }}
@if($loop->last)
$loop->index
@endif
@endforeach
<!-- Conditional -->
@if ($post->id === 1)
'Post one'
@elseif ($post->id === 2)
'Post two!'
@else
'Other'
@endif
<!-- Form -->
<form method="POST" action="{{ route('posts.store') }}">
@method(‘PUT’)
@csrf
<!-- Request path match -->
{{ request()->is('posts*') ? 'current page' : 'not current page' }}
<!-- Route exist? -->
@if (Route::has('login'))
<!-- Auth blade variable -->
@auth
@endauth
@guest
<!-- Current user -->
{{ Auth::user()->name }}
<!-- Validations errors -->
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<!-- Check a specific attributes -->
<input id="title" type="text" class="@error('title') is-invalid @enderror">
<!-- Repopulate form with data from previous request -->
{{ old('name') }}
@extends('layout.name')
@section('name') // Begin a section
@stop // End a section
@show // End a section and then show it
@yield('name') // Show a section name in a template
@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
{{ $var }} // Echo content
{{{ $var }}} // Echo escaped content
{{-- Blade Comment --}}
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::token();
Form::model($foo, array('route' => array('foo.bar', $foo->bar)));
Form::close;
Form Elements
Form::label('id', 'Description');
Form::label('id', 'Description', array('class' => 'foo'));
Form::text('name');
Form::text('name', $value);
Form::textarea('name');
Form::textarea('name', $value);
Form::textarea('name', $value, array('class' => 'name'));
Form::hidden('foo', $value);
Form::password('password');
Form::email('name', $value, array());
Form::file('name', array());
Form::checkbox('name', 'value');
Form::radio('name', 'value');
Form::select('name', array('key' => 'value'));
Form::select('name', array('key' => 'value'), 'key');
Form::submit('Submit!');
Form::input(‘type’, ‘name’, ‘value’) // type can be number…
Form Macros
Form::macro('fooField', function()
{ return '<input type="custom"/>'; });
Form::fooField();
HTML Builder
HTML::macro('name', function(){});
HTML::entities($value);
HTML::decode($value);
HTML::script($url, $attributes);
HTML::style($url, $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);
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)
Helpers Arrays
array_add($array, 'key', 'value');
array_build($array, function(){});
array_divide($array);
array_dot($array);
array_except($array, array('key'));
array_fetch($array, 'key');
array_first($array, function($key, $value){}, $default);
// Strips keys from the array
array_flatten($array);
array_forget($array, 'foo');
// Dot notation
array_forget($array, 'foo.bar');
array_get($array, 'foo', 'default');
array_get($array, 'foo.bar', 'default');
array_only($array, array('key'));
// Return array of key => values
array_pluck($array, 'key');
// Return and remove 'key' from array
array_pull($array, 'key');
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();
public_path();
// App root path
base_path();
storage_path();
Strings
camel_case($value);
class_basename($class);
// Escape a string
e('<html>');
starts_with('Foo bar.', 'Foo');
ends_with('Foo bar.', 'bar.');
snake_case('fooBar');
str_contains('Hello foo bar.', 'foo');
// Result: foo/bar/
str_finish('foo/bar', '/');
str_is('foo*', 'foobar');
str_plural('car');
str_random(25);
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();
clear cache
php artisan optimize:clear This will remove: The config cache = php artisan config:clear The compiled classes cache = The events cache = php artisan event:cache && php artisan event:clear The data cache (or application cache) = php artisan cache:clear The routes cache = php artisan route:clear The views cache = php artisan view:clear the scheduled tasks = php artisan schedule:clear-cache
to completly turn off the cache, set in your .env file
CACHE_DRIVER=null