50 Laravel Tricks in 50 Minutes

Azim Kurtaliev
Azim KurtalievGruzchik em завод
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
class Post extends Eloquent
{
public static $autoValidate = true;
protected static $rules = array();
protected static function boot()
{
parent::boot();
// You can also replace this with static::creating or static::updating
static::saving(function($model)
{
if ($model::$autoValidate)
{
return $model->validate();
}
});
}
public function validate()
{
}
}
class Post extends Eloquent
{
protected static function boot()
{
parent::boot();
static::updating(function($model)
{
return false;
});
}
}
class myModel extents Model
{
public function category()
{
return $this->belongsTo('myCategoryModel', 'categories_id')
->where('users_id', Auth::user()->id);
}
}
$products = Product::where('category', '=', 3)->get();
$products = Product::where('category', 3)->get();
$products = Product::whereCategory(3)->get();
SELECT *, COUNT(*) FROM products GROUP BY category_id HAVING count(*) > 1;
DB::table('products')
->select('*', DB::raw('COUNT(*) as products_count'))
->groupBy('category_id')
->having('products_count', '>' , 1)
->get();
Product::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get();
$q->whereDate('created_at', date('Y-m-d'));
$q->whereDay('created_at', date('d'));
$q->whereMonth('created_at', date('m'));
$q->whereYear('created_at', date('Y'));
// src/Illuminate/Database/Eloquent/Model.php
public function save(array $options = array())
// src/Illuminate/Database/Eloquent/Model.php
protected function performUpdate(Builder $query, array $options = [])
{
if ($this->timestamps && array_get($options, 'timestamps', true))
{
$this->updateTimestamps();
}
$product = Product::find($id);
$product->updated_at = '2015-01-01 10:00:00';
$product->save(['timestamps' => false]);
// app/Article.php
class Article extends Model
{
use DimsavTranslatableTranslatable;
public $translatedAttributes = ['name', 'text'];
}
// database/migrations/create_articles_table.php
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->boolean('online');
$table->timestamps();
});
}
// resources/views/article.blade.php
<h1>{{ $article->name }}</h1>
{{ $article->text }}
//database/migrations/create_articles_table.php
public function up()
{
$table->increments('id');
$table->integer('article_id')->unsigned();
$table->string('locale')->index();
$table->string('name');
$table->text('text');
$table->unique(['article_id','locale']);
$table->foreign('article_id')->references('id')
->on('articles')
->onDelete('cascade');
}
// app/ArticleTranslation.php
class ArticleTranslation extends Model
{
public $timestamps = false;
}
// app/http/routes.php
Route::get('{locale}', function($locale) {
app()->setLocale($locale);
$article = Article::first();
return view('article')->with(compact('article'));
});
http://50LaravelTricksIn50Minutes.com/fr -- French Translation
$questions = Question::orderByRaw('RAND()')->take(10)->get();
use RamseyUuidUuid;
trait UUIDModel
{
public $incrementing = false;
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$key = $model->getKeyName();
if (empty($model->{$key})) {
$model->{$key} = (string) $model->generateNewId();
}
});
}
public function generateNewUuid()
{
return Uuid::uuid4();
}
}
50 Laravel Tricks in 50 Minutes
class Category extends Model
{
public function products()
{
return $this->hasMany('AppProduct')->orderBy(‘name');
}
}
$customer = Customer::find($customer_id);
$loyalty_points = $customer->loyalty_points + 50;
$customer->update(['loyalty_points' => $loyalty_points]);
// adds one loyalty point
Customer::find($customer_id)->increment('loyalty_points', 50);
// subtracts one loyalty point
Customer::find($customer_id)->decrement('loyalty_points', 50);
$employees = Employee::where('branch_id', 9)->lists('name', 'id');
return view('customers.create', compact('employees'));
{!! Form::select('employee_id', $employees, '') !!}
public function getFullNameAttribute() {
return $this->name . ' ' . $this->surname;
}
[2015-07-19 21:47:19] local.ERROR: exception 'PDOException'
with message 'SQLSTATE[42S22]: Column not found:
1054 Unknown column 'full_name' in 'field list'' in
...vendorlaravelframeworksrcIlluminateDatabaseConnection.php:288
$employees = Employee::where('branch_id', 9)->get()->lists('full_name', 'id');
function getFullNameAttribute() {
return $this->first_name . ' ' . $this->last_name;
}
{
"id":1,
"first_name":"Povilas",
"last_name":"Korop",
"email":"povilas@webcoderpro.com",
"created_at":"2015-06-19 08:16:58",
"updated_at":"2015-06-19 19:48:09"
}
class User extends Model
{
protected $appends = ['full_name'];
{
"id":1,
"first_name":"Povilas",
"last_name":"Korop",
"email":"povilas@webcoderpro.com",
"created_at":"2015-06-19 08:16:58",
"updated_at":"2015-06-19 19:48:09",
"full_name":"Povilas Korop"
}
class Category extends Model
{
public function products() {
return $this->hasMany('AppProduct');
}
}
public function getIndex() {
$categories = Category::with('products')->has('products')->get();
return view('categories.index', compact('categories'));
}
public function store()
{
$post = new Post;
$post->fill(Input::all());
$post->user_id = Auth::user()->user_id;
$post->user;
return $post->save()
}
50 Laravel Tricks in 50 Minutes
// eloquent
Post::whereSlug('slug')->get();
// instead of
View::make('posts.index')->with(‘posts’, $posts);
// do this
View::make('posts.index')->withPosts($posts);
//hide all but the first item
@foreach ($menu as $item)
<div @if ($item != reset($menu)) class="hidden" @endif>
<h2>{{ $item->title }}</h2>
</div>
@endforeach
//apply css to last item only
@foreach ($menu as $item)
<div @if ($item == end($menu)) class="no_margin" @endif>
<h2>{{ $item->title }}</h2>
</div>
@endforeach
50 Laravel Tricks in 50 Minutes
$devs = [
['name' => 'Anouar Abdessalam','email' => 'dtekind@gmail.com'],
['name' => 'Bilal Ararou','email' => 'have@noIdea.com']
];
$devs = new IlluminateSupportCollection($devs);
$devs->first();
$devs->last();
$devs->push(['name' => 'xroot','email' => 'xroot@root.com']);
$customers = Customer::all();
$us_customers = $customers->filter(function ($customer) {
return $customer->country == 'United States';
});
$non_uk_customers = $customers->reject(function ($customer) {
return $customer->country == 'United Kingdom';
});
50 Laravel Tricks in 50 Minutes
// returns a single row as a collection
$collection = AppPerson::find([1]);
// can return multiple rows as a collection
$collection = AppPerson::find([1, 2, 3]);
$collection = AppPerson::all();
$programmers = $collection->where('type', 'programmer');
$critic = $collection->where('type', 'critic');
$engineer = $collection->where('type', 'engineer');
$collection = AppPerson::all();
$names = $collection->implode('first_name', ',');
// returns a collection of first names
$collection = AppPerson::all()->where('type', 'engineer')->lists('first_name');
// returns all the meta records for user 1
$collection = AppWP_Meta::whereUserId(1)->get();
// returns the first & last name meta values
$first_name = $collection->where('meta_key', 'first_name')->lists('value')[0];
$last_name = $collection->where('meta_key', 'last_name')->lists('value')[0];
class Link extends Model
{
public function users()
{
return $this->belongsToMany('PhpleaksUser')->withTimestamps();
}
}
@if ($link->users->count() > 0)
<strong>Recently Favorited By</strong>
@foreach ($link->users()->orderBy('link_user.created_at', 'desc')->take(15)->get() as $user)
<p>
<a href="{{ URL::Route('user.show', array('id' => $user->id)) }}">{{ $user->name }}</a>
</p>
@endforeach
@endif
$collection = collect([
['name' => 'Desk'],
['name' => 'Chair'],
['name' => 'Bookcase']
]);
$sorted = $collection->sortBy(function ($product, $key)
{
return array_search($product['name'], [1=>'Bookcase', 2=>'Desk', 3=>'Chair']);
});
$library = $books->keyBy('title');
[
'Lean Startup' => ['title' => 'Lean Startup', 'price' => 10],
'The One Thing' => ['title' => 'The One Thing', 'price' => 15],
'Laravel: Code Bright' => ['title' => 'Laravel: Code Bright', 'price' => 20],
'The 4-Hour Work Week' => ['title' => 'The 4-Hour Work Week', 'price' => 5],
]
$collection = AppPerson::all();
$grouped = $collection->groupBy('type');
// the point is to actually combine results from different models
$programmers = AppPerson::where('type', 'programmer')->get();
$critic = AppPerson::where('type', 'critic')->get();
$engineer = AppPerson::where('type', 'engineer')->get();
$collection = new Collection;
$all = $collection->merge($programmers)->merge($critic)->merge($engineer);
$collection = collect([1=>11, 5=>13, 12=>14, 21=>15])->getCachingIterator();
foreach ($collection as $key => $value) {
dump($collection->current() . ':' . $collection->getInnerIterator()->current());
}
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
Route::group(['prefix' => 'account', 'as' => 'account.'], function () {
Route::get('login', ['as' => 'login', 'uses' => 'AccountController@getLogin']);
Route::get('register', ['as' => 'register', 'uses' => 'AccountController@getRegister']);
Route::group(['middleware' => 'auth'], function () {
Route::get('edit', ['as' => 'edit', 'uses' => 'AccountController@getEdit']);
});
});
<a href="{{ route('account.login') }}">Login</a>
<a href="{{ route('account.register') }}">Register</a>
<a href="{{ route('account.edit') }}">Edit Account</a>
// app/Http/routes.php
Route::group(['middleware' => 'auth'], function () {
Route::get('{view}', function ($view) {
try {
return view($view);
} catch (Exception $e) {
abort(404);
}
})->where('view', '.*');
});
// api controller
public function show(Car $car)
{
if (Input::has('fields')) {
// do something
}
}
// internal request to api - fields are lost
$request = Request::create('/api/cars/' . $id . '?fields=id,color', 'GET');
$response = json_decode(Route::dispatch($request)->getContent());
// internal request to api - with fields
$originalInput = Request::input();
$request = Request::create('/api/cars/' . $id . '?fields=id,color', 'GET');
Request::replace($request->input());
$response = json_decode(Route::dispatch($request)->getContent());
Request::replace($originalInput);
50 Laravel Tricks in 50 Minutes
// phpunit.xml
<php>
<env name="APP_ENV" value="testing"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="TWILIO_FROM_NUMBER" value="+15005550006"/>
</php>
// .env.test – add to .gitignore
TWILIO_ACCOUNT_SID=fillmein
TWILIO_ACCOUNT_TOKEN=fillmein
// tests/TestCase.php
<?php
class TestCase extends IlluminateFoundationTestingTestCase
{
/**
* The base URL to use while testing the application.
*
* @var string
*/
protected $baseUrl = 'http://localhost';
/**
* Creates the application.
*
* @return IlluminateFoundationApplication
*/
public function createApplication()
{
$app = require __DIR__.'/../bootstrap/app.php';
if (file_exists(dirname(__DIR__) . '/.env.test')) {
Dotenv::load(dirname(__DIR__), '.env.test');
}
$app->make(IlluminateContractsConsoleKernel::class)->bootstrap();
return $app;
}
}
// access directly from your tests using helper function
env('TWILIO_ACCOUNT_TOKEN');
// gulpfile.js
var elixir = require('laravel-elixir');
mix.phpUnit();
$ gulp tdd
50 Laravel Tricks in 50 Minutes
// app/Http/Middleware/EncryptCookies.php
protected $except = [
'shared_cookie'
];
Cookie::queue('shared_cookie', 'my_shared_value', 10080, null, '.example.com');
$ artisan make:model Books -m
$ composer require genealabs/laravel-sparkinstaller --dev
//
LaravelSparkProvidersSparkServiceProvider::class,
GeneaLabsLaravelSparkInstallerProvidersLaravelSparkInstallerServiceProvider::class,
// do not run php artisan spark:install
$ php artisan spark:upgrade
// backup /resources/views/home.blade.php or it will be overwritten
$ php artisan vendor:publish --tag=spark-full
<?php namespace AppExceptions;
use Exception;
use IlluminateFoundationExceptionsHandler as ExceptionHandler;
use SymfonyComponentDebugExceptionHandler as SymfonyDisplayer;
class Handler extends ExceptionHandler
{
protected function convertExceptionToResponse(Exception $e)
{
$debug = config('app.debug', false);
if ($debug) {
return (new SymfonyDisplayer($debug))->createResponse($e);
}
return response()->view('errors.default', ['exception' => $e], 500);
}
}
// app/Providers/AppServiceProvider.php
public function register()
{
$this->app->bind(
'IlluminateContractsAuthRegistrar',
'AppServicesRegistrar'
);
if ($this->app->environment('production')) {
$this->app->register('AppProvidersProductionErrorHandlerServiceProvider');
} else {
$this->app->register('AppProvidersVerboseErrorHandlerServiceProvider');
}
}
50 Laravel Tricks in 50 Minutes
public function up()
{
Schema::table('users', function($table)
{
$table->string('name', 50)->change();
});
}
$ composer require doctrine/dbal
if (view()->exists('emails.' . $template))
{
// ... sending an email to the customer
}
// bootstrap/app.php
// replace this:
$app = new IlluminateFoundationApplication(
realpath(__DIR__.'/../')
);
// with this:
$app = new FantabulousApplication(
realpath(__DIR__.'/../')
);
<?php namespace Fantabulous;
class Application extends IlluminateFoundationApplication
{
/**
* Get the path to the storage directory.
*
* @return string
*/
public function storagePath()
{
return $this->basePath.'/FantabulousStorage';
}
}
class fakeApiCaller
{
public function getResultsForPath($path)
{
return [
'status' => 200,
'body' => json_encode([
'title' => "Results for path [$path]"
]),
'headers' => [
"Content-Type" => "application/json"
]
];
}
}
$app->get('{path?}', function($path)
{
$result = Cache::remember($path, 60, function() use ($path) {
return (new fakeApiCaller)->getResultsForPath($path);
});
return response($result['body'], $result['status'], array_only(
$result['headers'], ['Content-Type', 'X-Pagination']
));
})->where('path', '.*');
$ composer create-project laravel/laravel your-project-name-here dev-develop
// composer.json
{
"require": {
"php": ">=5.5.9",
"laravel/framework": "5.2.*"
},
"minimum-stability": "dev"
}
$ composer update
DB::listen(function($query, $bindings, $time) {
var_dump($query);
var_dump($bindings);
var_dump($time);
});
Event::listen('illuminate.query', function($query) {
var_dump($query);
});
// app/Policies/AdminPolicy.php
class AdminPolicy
{
public function managePages($user)
{
return $user->hasRole(['Administrator', 'Content Editor']);
}
}
// app/Providers/AuthServiceProvider.php
public function boot(IlluminateContractsAuthAccessGateContract $gate)
{
foreach (get_class_methods(new AppPoliciesAdminPolicy) as $method) {
$gate->define($method, "AppPoliciesAdminPolicy@{$method}");
}
$this->registerPolicies($gate);
}
$this->authorize('managePages'); // in Controllers
@can('managePages') // in Blade Templates
$user->can('managePages'); // via Eloquent
$disk= Storage::disk('s3');
$disk->put($targetFile, file_get_contents($sourceFile));
$disk = Storage::disk('s3');
$disk->put($targetFile, fopen($sourceFile, 'r+'));
$disk = Storage::disk('s3');
$stream = $disk->getDriver()->readStream($sourceFileOnS3);
file_put_contents($targetFile, stream_get_contents($stream), FILE_APPEND);
$stream = Storage::disk('s3')->getDriver()->readStream($sourceFile);
Storage::disk('sftp')->put($targetFile, $stream)
$schedule->call(function () {
Storage::delete($logfile);
})->weekly();
$result = (new IlluminatePipelinePipeline($container)
->send($something)
->through('ClassOne', 'ClassTwo', 'ClassThree')
->then(function ($something) {
return 'foo';
});
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
class PurchasePodcastCommand extends Command
{
public $user;
public $podcast;
public function __construct(User $user, Podcast $podcast)
{
$this->user = $user;
$this->podcast = $podcast;
}
}
class PurchasePodcastCommandHandler
{
public function handle(BillingGateway $billing)
{
// Handle the logic to purchase the podcast...
event(new PodcastWasPurchased($this->user, $this->podcast));
}
}
class PodcastController extends Controller
{
public function purchasePodcastCommand($podcastId)
{
$this->dispatch(
new PurchasePodcast(Auth::user(), Podcast::findOrFail($podcastId))
);
}
}
class PurchasePodcast extends Command implements SelfHandling
{
protected $user;
protected $podcast;
public function __construct(User $user, Podcast $podcast)
{
$this->user = $user;
$this->podcast = $podcast;
}
public function handle(BillingGateway $billing)
{
// Handle the logic to purchase the podcast...
event(new PodcastWasPurchased($this->user, $this->podcast));
}
}
class PodcastController extends Controller
{
public function purchasePodcast($podcastId)
{
$this->dispatch(
new PurchasePodcast(Auth::user(), Podcast::findOrFail($podcastId))
);
}
}
class PodcastController extends Controller
{
public function purchasePodcast(PurchasePodcastRequest $request)
{
$this->dispatchFrom('FantabulousCommandsPurchasePodcastCommand', $request);
}
}
class PodcastController extends Controller
{
public function purchasePodcast(PurchasePodcastRequest $request)
{
$this->dispatchFrom('FantabulousCommandsPurchasePodcastCommand', $request, [
'firstName' => 'Taylor',
]);
}
}
class PurchasePodcast extends Command
implements ShouldBeQueued, SerializesModels
{
public $user;
public $podcast;
public function __construct(User $user, Podcast $podcast)
{
$this->user = $user;
$this->podcast = $podcast;
}
}
// AppProvidersBusServiceProvider::boot
$dispatcher->pipeThrough(['UseDatabaseTransactions', 'LogCommand']);
class UseDatabaseTransactions
{
public function handle($command, $next)
{
return DB::transaction(function() use ($command, $next)
{
return $next($command);
});
}
}
// AppProvidersBusServiceProvider::boot
$dispatcher->pipeThrough([function($command, $next)
{
return DB::transaction(function() use ($command, $next)
{
return $next($command);
});
}]);
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
// app/http/routes.php
Route::get('/api/posts/{post}', function(Post $post) {
return $post;
});
// behind the scenes
Post::findOrFail($post);
$schedule->command('emails:send')
->hourly()
->appendOutputTo($filePath);
// returns titles for all posts
$titles = $posts->pluck(‘posts.*.title’);
<p>
<input type="text" name="person[1][id]">
<input type="text" name="person[1][name]">
</p>
<p>
<input type="text" name="person[2][id]">
<input type="text" name="person[2][name]">
</p>
$v = Validator::make($request->all(), [
'person.*.id' => 'exists:users.id',
'person.*.name' => 'required:string',
]);
// included in database session driver
user_id
ip_address
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
1 de 83

Recomendados

Dig Deeper into WordPress - WD Meetup Cairo por
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoMohamed Mosaad
934 visualizações16 slides
Symfony2 Building on Alpha / Beta technology por
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
750 visualizações59 slides
Hacking Your Way To Better Security - Dutch PHP Conference 2016 por
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Colin O'Dell
863 visualizações109 slides
購物車程式架構簡介 por
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介Jace Ju
19.7K visualizações171 slides
Your code sucks, let's fix it - DPC UnCon por
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConRafael Dohms
32.5K visualizações56 slides
Symfony2, creare bundle e valore per il cliente por
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteLeonardo Proietti
1.3K visualizações73 slides

Mais conteúdo relacionado

Mais procurados

“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf por
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonfRafael Dohms
3.9K visualizações82 slides
The Zen of Lithium por
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
2.6K visualizações118 slides
Backbone - TDC 2011 Floripa por
Backbone - TDC 2011 FloripaBackbone - TDC 2011 Floripa
Backbone - TDC 2011 FloripaRafael Felix da Silva
759 visualizações102 slides
Gail villanueva add muscle to your wordpress site por
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress sitereferences
2.8K visualizações39 slides
Propel sfugmd por
Propel sfugmdPropel sfugmd
Propel sfugmdiKlaus
464 visualizações22 slides
Be RESTful (Symfony Camp 2008) por
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Fabien Potencier
1.2K visualizações50 slides

Mais procurados(20)

“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf por Rafael Dohms
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
Rafael Dohms3.9K visualizações
The Zen of Lithium por Nate Abele
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
Nate Abele2.6K visualizações
Gail villanueva add muscle to your wordpress site por references
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress site
references2.8K visualizações
Propel sfugmd por iKlaus
Propel sfugmdPropel sfugmd
Propel sfugmd
iKlaus464 visualizações
Be RESTful (Symfony Camp 2008) por Fabien Potencier
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
Fabien Potencier1.2K visualizações
Doctrine For Beginners por Jonathan Wage
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage1.5K visualizações
Aplicacoes dinamicas Rails com Backbone por Rafael Felix da Silva
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
Rafael Felix da Silva1.1K visualizações
Dependency injection-zendcon-2010 por Fabien Potencier
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
Fabien Potencier9.3K visualizações
Dependency injection in PHP 5.3/5.4 por Fabien Potencier
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4
Fabien Potencier37.4K visualizações
Internationalizing CakePHP Applications por Pierre MARTIN
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP Applications
Pierre MARTIN5.8K visualizações
Separation of concerns - DPC12 por Stephan Hochdörfer
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12
Stephan Hochdörfer2.3K visualizações
Adding Dependency Injection to Legacy Applications por Sam Hennessy
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
Sam Hennessy1.8K visualizações
Drupal - dbtng 25th Anniversary Edition por ddiers
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
ddiers2.7K visualizações
WordPress as an application framework por Dustin Filippini
WordPress as an application frameworkWordPress as an application framework
WordPress as an application framework
Dustin Filippini416 visualizações
Laravel por Sayed Ahmed
LaravelLaravel
Laravel
Sayed Ahmed237 visualizações
Moving a high traffic ZF1 Enterprise Application to SF2 - Lessons learned por Baldur Rensch
Moving a high traffic ZF1 Enterprise Application to SF2 - Lessons learnedMoving a high traffic ZF1 Enterprise Application to SF2 - Lessons learned
Moving a high traffic ZF1 Enterprise Application to SF2 - Lessons learned
Baldur Rensch4.2K visualizações
PHPUnit でよりよくテストを書くために por Yuya Takeyama
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くために
Yuya Takeyama9.7K visualizações

Similar a 50 Laravel Tricks in 50 Minutes

Oops in php por
Oops in phpOops in php
Oops in phpGourishankar R Pujar
789 visualizações52 slides
You code sucks, let's fix it por
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix itRafael Dohms
56.4K visualizações56 slides
Dependency Injection por
Dependency InjectionDependency Injection
Dependency InjectionRifat Nabi
2.8K visualizações34 slides
Tidy Up Your Code por
Tidy Up Your CodeTidy Up Your Code
Tidy Up Your CodeAbbas Ali
3 visualizações52 slides
Bag Of Tricks From Iusethis por
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From IusethisMarcus Ramberg
6.4K visualizações88 slides
Virtual Madness @ Etsy por
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
524 visualizações28 slides

Similar a 50 Laravel Tricks in 50 Minutes(20)

You code sucks, let's fix it por Rafael Dohms
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
Rafael Dohms56.4K visualizações
Dependency Injection por Rifat Nabi
Dependency InjectionDependency Injection
Dependency Injection
Rifat Nabi2.8K visualizações
Tidy Up Your Code por Abbas Ali
Tidy Up Your CodeTidy Up Your Code
Tidy Up Your Code
Abbas Ali3 visualizações
Bag Of Tricks From Iusethis por Marcus Ramberg
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
Marcus Ramberg6.4K visualizações
Virtual Madness @ Etsy por Nishan Subedi
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
Nishan Subedi524 visualizações
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011 por camp_drupal_ua
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
camp_drupal_ua1.4K visualizações
The State of Lithium por Nate Abele
The State of LithiumThe State of Lithium
The State of Lithium
Nate Abele2.3K visualizações
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011 por Alessandro Nadalin
 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
Alessandro Nadalin9.4K visualizações
Rich domain model with symfony 2.5 and doctrine 2.5 por Leonardo Proietti
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
Leonardo Proietti12K visualizações
Crafting beautiful software por Jorn Oomen
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful software
Jorn Oomen2K visualizações
OOP in PHP.pptx por switipatel4
OOP in PHP.pptxOOP in PHP.pptx
OOP in PHP.pptx
switipatel46 visualizações
Unit testing zend framework apps por Michelangelo van Dam
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
Michelangelo van Dam2.6K visualizações
Drupal7 dbtng por Nicolas Leroy
Drupal7  dbtngDrupal7  dbtng
Drupal7 dbtng
Nicolas Leroy2.9K visualizações
Desarrollo de módulos en Drupal e integración con dispositivos móviles por Luis Curo Salvatierra
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Luis Curo Salvatierra389 visualizações
DrupalCamp Foz - Novas APIs Drupal 7 por chuvainc
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
chuvainc1.5K visualizações
Daily notes por meghendra168
Daily notesDaily notes
Daily notes
meghendra168885 visualizações
Lithium: The Framework for People Who Hate Frameworks por Nate Abele
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
Nate Abele12.2K visualizações

Último

Six Sigma Concept by Sahil Srivastava.pptx por
Six Sigma Concept by Sahil Srivastava.pptxSix Sigma Concept by Sahil Srivastava.pptx
Six Sigma Concept by Sahil Srivastava.pptxSahil Srivastava
51 visualizações11 slides
DISTILLATION.pptx por
DISTILLATION.pptxDISTILLATION.pptx
DISTILLATION.pptxAnupkumar Sharma
75 visualizações47 slides
REFERENCING, CITATION.pptx por
REFERENCING, CITATION.pptxREFERENCING, CITATION.pptx
REFERENCING, CITATION.pptxabhisrivastava11
41 visualizações26 slides
MercerJesse3.0.pdf por
MercerJesse3.0.pdfMercerJesse3.0.pdf
MercerJesse3.0.pdfjessemercerail
163 visualizações6 slides
JRN 362 - Lecture Twenty-Three (Epilogue) por
JRN 362 - Lecture Twenty-Three (Epilogue)JRN 362 - Lecture Twenty-Three (Epilogue)
JRN 362 - Lecture Twenty-Three (Epilogue)Rich Hanley
43 visualizações57 slides
Gross Anatomy of the Liver por
Gross Anatomy of the LiverGross Anatomy of the Liver
Gross Anatomy of the Liverobaje godwin sunday
89 visualizações12 slides

Último(20)

Six Sigma Concept by Sahil Srivastava.pptx por Sahil Srivastava
Six Sigma Concept by Sahil Srivastava.pptxSix Sigma Concept by Sahil Srivastava.pptx
Six Sigma Concept by Sahil Srivastava.pptx
Sahil Srivastava51 visualizações
DISTILLATION.pptx por Anupkumar Sharma
DISTILLATION.pptxDISTILLATION.pptx
DISTILLATION.pptx
Anupkumar Sharma75 visualizações
REFERENCING, CITATION.pptx por abhisrivastava11
REFERENCING, CITATION.pptxREFERENCING, CITATION.pptx
REFERENCING, CITATION.pptx
abhisrivastava1141 visualizações
MercerJesse3.0.pdf por jessemercerail
MercerJesse3.0.pdfMercerJesse3.0.pdf
MercerJesse3.0.pdf
jessemercerail163 visualizações
JRN 362 - Lecture Twenty-Three (Epilogue) por Rich Hanley
JRN 362 - Lecture Twenty-Three (Epilogue)JRN 362 - Lecture Twenty-Three (Epilogue)
JRN 362 - Lecture Twenty-Three (Epilogue)
Rich Hanley43 visualizações
Gross Anatomy of the Liver por obaje godwin sunday
Gross Anatomy of the LiverGross Anatomy of the Liver
Gross Anatomy of the Liver
obaje godwin sunday89 visualizações
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE... por Nguyen Thanh Tu Collection
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...
Nguyen Thanh Tu Collection100 visualizações
Ask The Expert! Nonprofit Website Tools, Tips, and Technology.pdf por TechSoup
 Ask The Expert! Nonprofit Website Tools, Tips, and Technology.pdf Ask The Expert! Nonprofit Website Tools, Tips, and Technology.pdf
Ask The Expert! Nonprofit Website Tools, Tips, and Technology.pdf
TechSoup 62 visualizações
Java Simplified: Understanding Programming Basics por Akshaj Vadakkath Joshy
Java Simplified: Understanding Programming BasicsJava Simplified: Understanding Programming Basics
Java Simplified: Understanding Programming Basics
Akshaj Vadakkath Joshy663 visualizações
Meet the Bible por Steve Thomason
Meet the BibleMeet the Bible
Meet the Bible
Steve Thomason81 visualizações
ICS3211_lecture 09_2023.pdf por Vanessa Camilleri
ICS3211_lecture 09_2023.pdfICS3211_lecture 09_2023.pdf
ICS3211_lecture 09_2023.pdf
Vanessa Camilleri147 visualizações
PRELIMS ANSWER.pptx por souravkrpodder
PRELIMS ANSWER.pptxPRELIMS ANSWER.pptx
PRELIMS ANSWER.pptx
souravkrpodder50 visualizações
Pharmaceutical Analysis PPT (BP 102T) por yakshpharmacy009
Pharmaceutical Analysis PPT (BP 102T) Pharmaceutical Analysis PPT (BP 102T)
Pharmaceutical Analysis PPT (BP 102T)
yakshpharmacy009116 visualizações
12.5.23 Poverty and Precarity.pptx por mary850239
12.5.23 Poverty and Precarity.pptx12.5.23 Poverty and Precarity.pptx
12.5.23 Poverty and Precarity.pptx
mary850239514 visualizações
Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37 por MysoreMuleSoftMeetup
Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37
Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37
MysoreMuleSoftMeetup54 visualizações
UNIT NO 13 ORGANISMS AND POPULATION.pptx por Madhuri Bhande
UNIT NO 13 ORGANISMS AND POPULATION.pptxUNIT NO 13 ORGANISMS AND POPULATION.pptx
UNIT NO 13 ORGANISMS AND POPULATION.pptx
Madhuri Bhande43 visualizações
Nelson_RecordStore.pdf por BrynNelson5
Nelson_RecordStore.pdfNelson_RecordStore.pdf
Nelson_RecordStore.pdf
BrynNelson550 visualizações
Guidelines & Identification of Early Sepsis DR. NN CHAVAN 02122023.pptx por Niranjan Chavan
Guidelines & Identification of Early Sepsis DR. NN CHAVAN 02122023.pptxGuidelines & Identification of Early Sepsis DR. NN CHAVAN 02122023.pptx
Guidelines & Identification of Early Sepsis DR. NN CHAVAN 02122023.pptx
Niranjan Chavan42 visualizações

50 Laravel Tricks in 50 Minutes

  • 6. class Post extends Eloquent { public static $autoValidate = true; protected static $rules = array(); protected static function boot() { parent::boot(); // You can also replace this with static::creating or static::updating static::saving(function($model) { if ($model::$autoValidate) { return $model->validate(); } }); } public function validate() { } }
  • 7. class Post extends Eloquent { protected static function boot() { parent::boot(); static::updating(function($model) { return false; }); } }
  • 8. class myModel extents Model { public function category() { return $this->belongsTo('myCategoryModel', 'categories_id') ->where('users_id', Auth::user()->id); } }
  • 9. $products = Product::where('category', '=', 3)->get(); $products = Product::where('category', 3)->get(); $products = Product::whereCategory(3)->get();
  • 10. SELECT *, COUNT(*) FROM products GROUP BY category_id HAVING count(*) > 1; DB::table('products') ->select('*', DB::raw('COUNT(*) as products_count')) ->groupBy('category_id') ->having('products_count', '>' , 1) ->get(); Product::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get();
  • 12. // src/Illuminate/Database/Eloquent/Model.php public function save(array $options = array()) // src/Illuminate/Database/Eloquent/Model.php protected function performUpdate(Builder $query, array $options = []) { if ($this->timestamps && array_get($options, 'timestamps', true)) { $this->updateTimestamps(); } $product = Product::find($id); $product->updated_at = '2015-01-01 10:00:00'; $product->save(['timestamps' => false]);
  • 13. // app/Article.php class Article extends Model { use DimsavTranslatableTranslatable; public $translatedAttributes = ['name', 'text']; } // database/migrations/create_articles_table.php public function up() { Schema::create('articles', function (Blueprint $table) { $table->increments('id'); $table->boolean('online'); $table->timestamps(); }); } // resources/views/article.blade.php <h1>{{ $article->name }}</h1> {{ $article->text }} //database/migrations/create_articles_table.php public function up() { $table->increments('id'); $table->integer('article_id')->unsigned(); $table->string('locale')->index(); $table->string('name'); $table->text('text'); $table->unique(['article_id','locale']); $table->foreign('article_id')->references('id') ->on('articles') ->onDelete('cascade'); } // app/ArticleTranslation.php class ArticleTranslation extends Model { public $timestamps = false; } // app/http/routes.php Route::get('{locale}', function($locale) { app()->setLocale($locale); $article = Article::first(); return view('article')->with(compact('article')); }); http://50LaravelTricksIn50Minutes.com/fr -- French Translation
  • 15. use RamseyUuidUuid; trait UUIDModel { public $incrementing = false; protected static function boot() { parent::boot(); static::creating(function ($model) { $key = $model->getKeyName(); if (empty($model->{$key})) { $model->{$key} = (string) $model->generateNewId(); } }); } public function generateNewUuid() { return Uuid::uuid4(); } }
  • 17. class Category extends Model { public function products() { return $this->hasMany('AppProduct')->orderBy(‘name'); } }
  • 18. $customer = Customer::find($customer_id); $loyalty_points = $customer->loyalty_points + 50; $customer->update(['loyalty_points' => $loyalty_points]); // adds one loyalty point Customer::find($customer_id)->increment('loyalty_points', 50); // subtracts one loyalty point Customer::find($customer_id)->decrement('loyalty_points', 50);
  • 19. $employees = Employee::where('branch_id', 9)->lists('name', 'id'); return view('customers.create', compact('employees')); {!! Form::select('employee_id', $employees, '') !!} public function getFullNameAttribute() { return $this->name . ' ' . $this->surname; } [2015-07-19 21:47:19] local.ERROR: exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'full_name' in 'field list'' in ...vendorlaravelframeworksrcIlluminateDatabaseConnection.php:288 $employees = Employee::where('branch_id', 9)->get()->lists('full_name', 'id');
  • 20. function getFullNameAttribute() { return $this->first_name . ' ' . $this->last_name; } { "id":1, "first_name":"Povilas", "last_name":"Korop", "email":"povilas@webcoderpro.com", "created_at":"2015-06-19 08:16:58", "updated_at":"2015-06-19 19:48:09" } class User extends Model { protected $appends = ['full_name']; { "id":1, "first_name":"Povilas", "last_name":"Korop", "email":"povilas@webcoderpro.com", "created_at":"2015-06-19 08:16:58", "updated_at":"2015-06-19 19:48:09", "full_name":"Povilas Korop" }
  • 21. class Category extends Model { public function products() { return $this->hasMany('AppProduct'); } } public function getIndex() { $categories = Category::with('products')->has('products')->get(); return view('categories.index', compact('categories')); }
  • 22. public function store() { $post = new Post; $post->fill(Input::all()); $post->user_id = Auth::user()->user_id; $post->user; return $post->save() }
  • 24. // eloquent Post::whereSlug('slug')->get(); // instead of View::make('posts.index')->with(‘posts’, $posts); // do this View::make('posts.index')->withPosts($posts);
  • 25. //hide all but the first item @foreach ($menu as $item) <div @if ($item != reset($menu)) class="hidden" @endif> <h2>{{ $item->title }}</h2> </div> @endforeach //apply css to last item only @foreach ($menu as $item) <div @if ($item == end($menu)) class="no_margin" @endif> <h2>{{ $item->title }}</h2> </div> @endforeach
  • 27. $devs = [ ['name' => 'Anouar Abdessalam','email' => 'dtekind@gmail.com'], ['name' => 'Bilal Ararou','email' => 'have@noIdea.com'] ]; $devs = new IlluminateSupportCollection($devs); $devs->first(); $devs->last(); $devs->push(['name' => 'xroot','email' => 'xroot@root.com']);
  • 28. $customers = Customer::all(); $us_customers = $customers->filter(function ($customer) { return $customer->country == 'United States'; }); $non_uk_customers = $customers->reject(function ($customer) { return $customer->country == 'United Kingdom'; });
  • 30. // returns a single row as a collection $collection = AppPerson::find([1]); // can return multiple rows as a collection $collection = AppPerson::find([1, 2, 3]);
  • 31. $collection = AppPerson::all(); $programmers = $collection->where('type', 'programmer'); $critic = $collection->where('type', 'critic'); $engineer = $collection->where('type', 'engineer');
  • 32. $collection = AppPerson::all(); $names = $collection->implode('first_name', ',');
  • 33. // returns a collection of first names $collection = AppPerson::all()->where('type', 'engineer')->lists('first_name'); // returns all the meta records for user 1 $collection = AppWP_Meta::whereUserId(1)->get(); // returns the first & last name meta values $first_name = $collection->where('meta_key', 'first_name')->lists('value')[0]; $last_name = $collection->where('meta_key', 'last_name')->lists('value')[0];
  • 34. class Link extends Model { public function users() { return $this->belongsToMany('PhpleaksUser')->withTimestamps(); } } @if ($link->users->count() > 0) <strong>Recently Favorited By</strong> @foreach ($link->users()->orderBy('link_user.created_at', 'desc')->take(15)->get() as $user) <p> <a href="{{ URL::Route('user.show', array('id' => $user->id)) }}">{{ $user->name }}</a> </p> @endforeach @endif
  • 35. $collection = collect([ ['name' => 'Desk'], ['name' => 'Chair'], ['name' => 'Bookcase'] ]); $sorted = $collection->sortBy(function ($product, $key) { return array_search($product['name'], [1=>'Bookcase', 2=>'Desk', 3=>'Chair']); });
  • 36. $library = $books->keyBy('title'); [ 'Lean Startup' => ['title' => 'Lean Startup', 'price' => 10], 'The One Thing' => ['title' => 'The One Thing', 'price' => 15], 'Laravel: Code Bright' => ['title' => 'Laravel: Code Bright', 'price' => 20], 'The 4-Hour Work Week' => ['title' => 'The 4-Hour Work Week', 'price' => 5], ]
  • 37. $collection = AppPerson::all(); $grouped = $collection->groupBy('type');
  • 38. // the point is to actually combine results from different models $programmers = AppPerson::where('type', 'programmer')->get(); $critic = AppPerson::where('type', 'critic')->get(); $engineer = AppPerson::where('type', 'engineer')->get(); $collection = new Collection; $all = $collection->merge($programmers)->merge($critic)->merge($engineer);
  • 39. $collection = collect([1=>11, 5=>13, 12=>14, 21=>15])->getCachingIterator(); foreach ($collection as $key => $value) { dump($collection->current() . ':' . $collection->getInnerIterator()->current()); }
  • 42. Route::group(['prefix' => 'account', 'as' => 'account.'], function () { Route::get('login', ['as' => 'login', 'uses' => 'AccountController@getLogin']); Route::get('register', ['as' => 'register', 'uses' => 'AccountController@getRegister']); Route::group(['middleware' => 'auth'], function () { Route::get('edit', ['as' => 'edit', 'uses' => 'AccountController@getEdit']); }); }); <a href="{{ route('account.login') }}">Login</a> <a href="{{ route('account.register') }}">Register</a> <a href="{{ route('account.edit') }}">Edit Account</a>
  • 43. // app/Http/routes.php Route::group(['middleware' => 'auth'], function () { Route::get('{view}', function ($view) { try { return view($view); } catch (Exception $e) { abort(404); } })->where('view', '.*'); });
  • 44. // api controller public function show(Car $car) { if (Input::has('fields')) { // do something } } // internal request to api - fields are lost $request = Request::create('/api/cars/' . $id . '?fields=id,color', 'GET'); $response = json_decode(Route::dispatch($request)->getContent()); // internal request to api - with fields $originalInput = Request::input(); $request = Request::create('/api/cars/' . $id . '?fields=id,color', 'GET'); Request::replace($request->input()); $response = json_decode(Route::dispatch($request)->getContent()); Request::replace($originalInput);
  • 46. // phpunit.xml <php> <env name="APP_ENV" value="testing"/> <env name="CACHE_DRIVER" value="array"/> <env name="SESSION_DRIVER" value="array"/> <env name="QUEUE_DRIVER" value="sync"/> <env name="DB_DATABASE" value=":memory:"/> <env name="DB_CONNECTION" value="sqlite"/> <env name="TWILIO_FROM_NUMBER" value="+15005550006"/> </php> // .env.test – add to .gitignore TWILIO_ACCOUNT_SID=fillmein TWILIO_ACCOUNT_TOKEN=fillmein // tests/TestCase.php <?php class TestCase extends IlluminateFoundationTestingTestCase { /** * The base URL to use while testing the application. * * @var string */ protected $baseUrl = 'http://localhost'; /** * Creates the application. * * @return IlluminateFoundationApplication */ public function createApplication() { $app = require __DIR__.'/../bootstrap/app.php'; if (file_exists(dirname(__DIR__) . '/.env.test')) { Dotenv::load(dirname(__DIR__), '.env.test'); } $app->make(IlluminateContractsConsoleKernel::class)->bootstrap(); return $app; } } // access directly from your tests using helper function env('TWILIO_ACCOUNT_TOKEN');
  • 47. // gulpfile.js var elixir = require('laravel-elixir'); mix.phpUnit(); $ gulp tdd
  • 49. // app/Http/Middleware/EncryptCookies.php protected $except = [ 'shared_cookie' ]; Cookie::queue('shared_cookie', 'my_shared_value', 10080, null, '.example.com');
  • 51. $ composer require genealabs/laravel-sparkinstaller --dev // LaravelSparkProvidersSparkServiceProvider::class, GeneaLabsLaravelSparkInstallerProvidersLaravelSparkInstallerServiceProvider::class, // do not run php artisan spark:install $ php artisan spark:upgrade // backup /resources/views/home.blade.php or it will be overwritten $ php artisan vendor:publish --tag=spark-full
  • 52. <?php namespace AppExceptions; use Exception; use IlluminateFoundationExceptionsHandler as ExceptionHandler; use SymfonyComponentDebugExceptionHandler as SymfonyDisplayer; class Handler extends ExceptionHandler { protected function convertExceptionToResponse(Exception $e) { $debug = config('app.debug', false); if ($debug) { return (new SymfonyDisplayer($debug))->createResponse($e); } return response()->view('errors.default', ['exception' => $e], 500); } }
  • 53. // app/Providers/AppServiceProvider.php public function register() { $this->app->bind( 'IlluminateContractsAuthRegistrar', 'AppServicesRegistrar' ); if ($this->app->environment('production')) { $this->app->register('AppProvidersProductionErrorHandlerServiceProvider'); } else { $this->app->register('AppProvidersVerboseErrorHandlerServiceProvider'); } }
  • 55. public function up() { Schema::table('users', function($table) { $table->string('name', 50)->change(); }); } $ composer require doctrine/dbal
  • 56. if (view()->exists('emails.' . $template)) { // ... sending an email to the customer }
  • 57. // bootstrap/app.php // replace this: $app = new IlluminateFoundationApplication( realpath(__DIR__.'/../') ); // with this: $app = new FantabulousApplication( realpath(__DIR__.'/../') ); <?php namespace Fantabulous; class Application extends IlluminateFoundationApplication { /** * Get the path to the storage directory. * * @return string */ public function storagePath() { return $this->basePath.'/FantabulousStorage'; } }
  • 58. class fakeApiCaller { public function getResultsForPath($path) { return [ 'status' => 200, 'body' => json_encode([ 'title' => "Results for path [$path]" ]), 'headers' => [ "Content-Type" => "application/json" ] ]; } } $app->get('{path?}', function($path) { $result = Cache::remember($path, 60, function() use ($path) { return (new fakeApiCaller)->getResultsForPath($path); }); return response($result['body'], $result['status'], array_only( $result['headers'], ['Content-Type', 'X-Pagination'] )); })->where('path', '.*');
  • 59. $ composer create-project laravel/laravel your-project-name-here dev-develop // composer.json { "require": { "php": ">=5.5.9", "laravel/framework": "5.2.*" }, "minimum-stability": "dev" } $ composer update
  • 60. DB::listen(function($query, $bindings, $time) { var_dump($query); var_dump($bindings); var_dump($time); }); Event::listen('illuminate.query', function($query) { var_dump($query); });
  • 61. // app/Policies/AdminPolicy.php class AdminPolicy { public function managePages($user) { return $user->hasRole(['Administrator', 'Content Editor']); } } // app/Providers/AuthServiceProvider.php public function boot(IlluminateContractsAuthAccessGateContract $gate) { foreach (get_class_methods(new AppPoliciesAdminPolicy) as $method) { $gate->define($method, "AppPoliciesAdminPolicy@{$method}"); } $this->registerPolicies($gate); } $this->authorize('managePages'); // in Controllers @can('managePages') // in Blade Templates $user->can('managePages'); // via Eloquent
  • 62. $disk= Storage::disk('s3'); $disk->put($targetFile, file_get_contents($sourceFile)); $disk = Storage::disk('s3'); $disk->put($targetFile, fopen($sourceFile, 'r+')); $disk = Storage::disk('s3'); $stream = $disk->getDriver()->readStream($sourceFileOnS3); file_put_contents($targetFile, stream_get_contents($stream), FILE_APPEND); $stream = Storage::disk('s3')->getDriver()->readStream($sourceFile); Storage::disk('sftp')->put($targetFile, $stream)
  • 64. $result = (new IlluminatePipelinePipeline($container) ->send($something) ->through('ClassOne', 'ClassTwo', 'ClassThree') ->then(function ($something) { return 'foo'; });
  • 68. class PurchasePodcastCommand extends Command { public $user; public $podcast; public function __construct(User $user, Podcast $podcast) { $this->user = $user; $this->podcast = $podcast; } } class PurchasePodcastCommandHandler { public function handle(BillingGateway $billing) { // Handle the logic to purchase the podcast... event(new PodcastWasPurchased($this->user, $this->podcast)); } } class PodcastController extends Controller { public function purchasePodcastCommand($podcastId) { $this->dispatch( new PurchasePodcast(Auth::user(), Podcast::findOrFail($podcastId)) ); } }
  • 69. class PurchasePodcast extends Command implements SelfHandling { protected $user; protected $podcast; public function __construct(User $user, Podcast $podcast) { $this->user = $user; $this->podcast = $podcast; } public function handle(BillingGateway $billing) { // Handle the logic to purchase the podcast... event(new PodcastWasPurchased($this->user, $this->podcast)); } } class PodcastController extends Controller { public function purchasePodcast($podcastId) { $this->dispatch( new PurchasePodcast(Auth::user(), Podcast::findOrFail($podcastId)) ); } }
  • 70. class PodcastController extends Controller { public function purchasePodcast(PurchasePodcastRequest $request) { $this->dispatchFrom('FantabulousCommandsPurchasePodcastCommand', $request); } } class PodcastController extends Controller { public function purchasePodcast(PurchasePodcastRequest $request) { $this->dispatchFrom('FantabulousCommandsPurchasePodcastCommand', $request, [ 'firstName' => 'Taylor', ]); } }
  • 71. class PurchasePodcast extends Command implements ShouldBeQueued, SerializesModels { public $user; public $podcast; public function __construct(User $user, Podcast $podcast) { $this->user = $user; $this->podcast = $podcast; } }
  • 72. // AppProvidersBusServiceProvider::boot $dispatcher->pipeThrough(['UseDatabaseTransactions', 'LogCommand']); class UseDatabaseTransactions { public function handle($command, $next) { return DB::transaction(function() use ($command, $next) { return $next($command); }); } } // AppProvidersBusServiceProvider::boot $dispatcher->pipeThrough([function($command, $next) { return DB::transaction(function() use ($command, $next) { return $next($command); }); }]);
  • 76. // app/http/routes.php Route::get('/api/posts/{post}', function(Post $post) { return $post; }); // behind the scenes Post::findOrFail($post);
  • 78. // returns titles for all posts $titles = $posts->pluck(‘posts.*.title’);
  • 79. <p> <input type="text" name="person[1][id]"> <input type="text" name="person[1][name]"> </p> <p> <input type="text" name="person[2][id]"> <input type="text" name="person[2][name]"> </p> $v = Validator::make($request->all(), [ 'person.*.id' => 'exists:users.id', 'person.*.name' => 'required:string', ]);
  • 80. // included in database session driver user_id ip_address