The package has been tested in the following configuration:
- PHP version >= 7.1.3
- Laravel Framework version >= 5.8
Require this package with composer using the following command:
composer require rvkolosov/laravel-withtrait
Enable trait in your model:
use RVKolosov\LaravelWithTrait\WithTrait;
use App\Models\Image;
class Post extends Model
{
use WithTrait;
public function images()
{
return $this->hasMany(Image::class);
}
}
For index method of controller use withRelations()
:
use App\Models\Post;
class PostController extends Controller
{
public function index()
{
return Post::withRelations()->get();
}
}
For show method of controller use loadRelations()
:
use App\Models\Post;
class PostController extends Controller
{
public function show(Post $post)
{
return $post->loadRelations();
}
}
You can dynamically load relations in GET
request.
Load relations for list:
GET http://example.com/post?with[]=images
Load relations for one object:
GET http://example.com/posts/1?with[]=images
The Laravel WithTrait is open-sourced software licensed under the MIT license