Laravel

laravel

Laravel is a web application framework with expressive, elegant syntax. Post tips, questions, news, anything related to Laravel

Laravel paginate Resource class

Resource

$data = SampleModel::paginate(10);
return ['key' => SampleModelResource::collection($data)->response()->getData(true)];
Show more

Laravel stubs

There is an easier way to create classes. Instead of creating User model from scratch you can type

php artisan make:model User

It is generated by stubs modules. If you want to change default one, first publish stubs:

php artisan stub:publish

And edit as you like:

 

Now, every time you create model with stub, $guarded is set to empty.

Show more

Global Scope | booted method

Let's say you are trying to get users where active column is 1. Instead of writing every time

User::where('active',1);,

we can use Global Scopes. 

  • Create YourScope.php file inside app/Scopes folder.
  • Paste following code
<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class YourScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
       $builder->where('active', 1);
    }
}
  • And inside your Model add
protected static function booted()
{
  static::addGlobalScope(new YourScope());
}

Now, you when you call Users, you get only active ones.

Show more