rvkolosov/laravel-withtrait

WithTrait for dynamic load relations in Laravel Model.

dev-master 2019-06-21 19:51 UTC

This package is auto-updated.

Last update: 2024-04-22 06:39:12 UTC


README

Latest Version on Packagist Software License Build Status Total Downloads

Requirements

The package has been tested in the following configuration:

  • PHP version >= 7.1.3
  • Laravel Framework version >= 5.8

Install

Require this package with composer using the following command:

composer require rvkolosov/laravel-withtrait

Configuration

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

Usage

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

License

The Laravel WithTrait is open-sourced software licensed under the MIT license