Laravel Tricks in 50 Minutes
Laravel Tricks in 50 Minutes
{
public static $autoValidate = true;
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::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();
$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]);
// database/migrations/create_articles_table.php // app/Article.php
public function up() class Article extends Model
{ {
Schema::create('articles', function (Blueprint $table) { use \Dimsav\Translatable\Translatable;
$table->increments('id');
$table->boolean('online'); public $translatedAttributes = ['name', 'text'];
$table->timestamps(); }
});
}
// app/ArticleTranslation.php
class ArticleTranslation extends Model
//database/migrations/create_articles_table.php {
public function up() public $timestamps = false;
{ }
$table->increments('id');
$table->integer('article_id')->unsigned();
$table->string('locale')->index();
// app/http/routes.php
$table->string('name'); Route::get('{locale}', function($locale) {
$table->text('text'); app()->setLocale($locale);
$article = Article::first();
$table->unique(['article_id','locale']);
$table->foreign('article_id')->references('id') return view('article')->with(compact('article'));
->on('articles') });
->onDelete('cascade');
}
// resources/views/article.blade.php
<h1>{{ $article->name }}</h1>
http://50LaravelTricksIn50Minutes.com/fr -- French Translation {{ $article->text }}
$questions = Question::orderByRaw('RAND()')->take(10)->get();
use Ramsey\Uuid\Uuid;
trait UUIDModel
{
public $incrementing = false;
static::creating(function ($model) {
$key = $model->getKeyName();
if (empty($model->{$key})) {
$model->{$key} = (string) $model->generateNewId();
}
});
}
{
"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"
}
{
"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('App\Product');
}
}
$post->user;
return $post->save()
}
// 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
$devs->first();
$devs->last();
$devs->push(['name' => 'xroot','email' => 'xroot@root.com']);
$customers = Customer::all();
<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']
]);
[
'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 = App\Person::all();
$grouped = $collection->groupBy('type');
// the point is to actually combine results from different models
$programmers = \App\Person::where('type', 'programmer')->get();
$critic = \App\Person::where('type', 'critic')->get();
$engineer = \App\Person::where('type', 'engineer')->get();
$all = $collection->merge($programmers)->merge($critic)->merge($engineer);
$collection = collect([1=>11, 5=>13, 12=>14, 21=>15])->getCachingIterator();
});
/**
// .env.test – add to .gitignore * Creates the application.
TWILIO_ACCOUNT_SID=fillmein *
TWILIO_ACCOUNT_TOKEN=fillmein * @return \Illuminate\Foundation\Application
*/
public function createApplication()
{
$app = require __DIR__.'/../bootstrap/app.php';
// access directly from your tests using helper function
env('TWILIO_ACCOUNT_TOKEN'); if (file_exists(dirname(__DIR__) . '/.env.test')) {
Dotenv::load(dirname(__DIR__), '.env.test');
}
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
return $app;
}
}
// gulpfile.js
var elixir = require('laravel-elixir');
mix.phpUnit();
$ gulp tdd
// app/Http/Middleware/EncryptCookies.php
protected $except = [
'shared_cookie'
];
//
Laravel\Spark\Providers\SparkServiceProvider::class,
GeneaLabs\LaravelSparkInstaller\Providers\LaravelSparkInstallerServiceProvider::class,
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\Debug\ExceptionHandler as SymfonyDisplayer;
if ($debug) {
return (new SymfonyDisplayer($debug))->createResponse($e);
}
if ($this->app->environment('production')) {
$this->app->register('App\Providers\ProductionErrorHandlerServiceProvider');
} else {
$this->app->register('App\Providers\VerboseErrorHandlerServiceProvider');
}
}
$ composer require doctrine/dbal
// with this:
$app = new Fantabulous\Application(
realpath(__DIR__.'/../')
);
$app->get('{path?}', function($path)
{
$result = Cache::remember($path, 60, function() use ($path) {
return (new fakeApiCaller)->getResultsForPath($path);
});
// composer.json
{
"require": {
"php": ">=5.5.9",
"laravel/framework": "5.2.*"
},
"minimum-stability": "dev"
}
$ composer update
Event::listen('illuminate.query', function($query) {
var_dump($query);
});
// app/Providers/AuthServiceProvider.php
public function boot(\Illuminate\Contracts\Auth\Access\GateContract $gate)
{
foreach (get_class_methods(new \App\Policies\AdminPolicy) as $method) {
$gate->define($method, "App\Policies\AdminPolicy@{$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 Illuminate\Pipeline\Pipeline($container)
->send($something)
->through('ClassOne', 'ClassTwo', 'ClassThree')
->then(function ($something) {
return 'foo';
});
class PurchasePodcastCommand extends Command
{
public $user;
public $podcast;
class PurchasePodcastCommandHandler
{
public function handle(BillingGateway $billing)
{
// Handle the logic to purchase the podcast...
class UseDatabaseTransactions
{
public function handle($command, $next)
{
return DB::transaction(function() use ($command, $next)
{
return $next($command);
});
}
}
// App\Providers\BusServiceProvider::boot
$dispatcher->pipeThrough([function($command, $next)
{
return DB::transaction(function() use ($command, $next)
{
return $next($command);
});
}]);
// app/http/routes.php
Route::get('/api/posts/{post}', function(Post $post) {
return $post;
});
$v = Validator::make($request->all(), [
'person.*.id' => 'exists:users.id',
'person.*.name' => 'required:string',
]);
// included in database session driver
user_id
ip_address