Skip to content

Instantly share code, notes, and snippets.

@Bunix
Forked from cjthomp/50 Laravel Tricks.md
Created October 10, 2018 08:21
Show Gist options
  • Select an option

  • Save Bunix/1d1257de5b43b427bbfa10dca2daea5a to your computer and use it in GitHub Desktop.

Select an option

Save Bunix/1d1257de5b43b427bbfa10dca2daea5a to your computer and use it in GitHub Desktop.
50 Laravel Tricks

Reference

  1. https://speakerdeck.com/willroth/50-laravel-tricks-in-50-minutes
  2. https://www.reddit.com/r/laravel/comments/3to60i/50_laravel_tricks/

ELOQUENT

1. Automatic Model Validation

class Post extends Eloquent
{
	public staic $autoValidates = true;

	protected static $rules = [];

	protected static function boot()
	{
		parent::boot();

		// or static::creating, or static::updating
		static::saving(function($model)
		{
			if ($model::$autoValidates) {
				return $model->validate();
			}
		});
	}

	public function validate()
	{

	}
}

2. Prevent updating

class Post extends Eloquent
{
	protected static function boot()
	{
		parent::boot();

		static::updating(function($model)
		{
			return false;
		});
	}
}

3. Conditional Relationships

class myModel extends Model
{
	public function category()
	{
		return $this->belongsTo('myCategoryModel', 'categories_id')
			->where('users_id', Auth::user()->id);
	}
}

4. Expressive "Where" Syntax

$products = Product::where('category', '=', 3)->get();

$products = Product::where('category', 3)->get();

$products = Product::whereCategory(3)->get();

5. Query Builder: Having Raw

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();

6. Simple Date Filtering

$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'));

7. Save Options

// src/Illuminate/Database/Eloquent/Model.php
public function save(array $options = [])

// 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 00:00:00';
$product->save(['timestamps'=>false]);

8. Multilanguage Support

// TODO

9. Retrieve Random Rows

$questions = Question::orderByRaw('RAND()')->take(10)->get();

10. UUID Model Primary Key

use Ramsey\Uuid\Uuid;

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();
	}
}

11. Ordered Relationships

class Category extends Model
{
	public function products()
	{
		return $this->hasMany('App\Product')->orderBy('name');
	}
}

12. Simple Incrementing & Decrementing

$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);

13. Lists with Mutations

// TODO

14. Appending Mutated Properties

// TODO

15. Filter only rows with child rows

class Category extends Model
{
	public function products()
	{
		return $this->hasMany('App\Product');
	}
}

public function getIndex()
{
	$categories = Category::with('products')->has('products')->get();
	return view('categories.index', compact('categories'));
}

16. Return relations on model save

public function store()
{
	$post = new Post;
	$post->fill(Input::all());
	$post->user_id = Auth::user()->user_id;

	$post->user;

	return $post->save();
}

Blade

17.

18.

19.

20.

21.

22.

23.

24.

25.

26.

27.

28.

29.

30.

31.

32.

33.

34.

35.

36.

37.

38.

39.

40.

41.

42.

43.

44.

45.

46.

47.

48.

49.

50.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment