mercredi 5 septembre 2018

Responses JSON with Relationship - Laravel/Eloquente

I'm working on a Laravel project and I want to create a REST API for a website. On my system, I have two tables:

Blogs and Categories. The table blogs have the category_id column, which is a key that references the column ID in the category table.

Blogs Migration

class CreateBlogsTable extends Migration
{
    public function up()
    {
     Schema::create('blogs', function (Blueprint $table) {
     $table->increments('id');
     $table->string('title');
     $table->longtext('body');
     $table->string('category_id');
     $table->timestamps();
    });
   }
   .....
}

Categories Migration

class CreateCategoriesTable extends Migration
{
    public function up()
    {
     Schema::create('categories', function (Blueprint $table) {
     $table->increments('id');
     $table->string('name');
     $table->timestamps();
    });
   }
   ....
}

My blogs Model

class Blog extends Model
{
    protected $fillable = ['title', 'body', 'category_id'];
    public function category() {
       return $this->hasMany('app\Category');
    }
}

My blogs Model

class Category extends Model
{
    protected $fillable = ['name'];
    public function blog() {
       return $this->hasMany('app\Blog');
    }
}

So, I created a BlogController and configured the routes to access the corresponding API function.

The api / blogs / via GET is for the index function of my controller, and the function looks like this:

public function index()
{
    $blog = Blog::all();
    return response()->json($blog, 200);
}

With this, I can get the data from the blogs table

[
    {
        "id": 1,
        "title": "title from my blog",
        "text": "text body here",
        "category_id": "2",
        "created_at": "2018-09-05 21:08:21",
        "updated_at": "2018-09-05 21:08:21"
    }
]

but I would like to merge the table of blogs and categories, and get a similar response to this

[
    {
        "id": 1,
        "title": "title from my blog",
        "text": "text body here",
        "category_id": "2",
        "created_at": "2018-09-05 21:08:21",
        "updated_at": "2018-09-05 21:08:21"
        "category": [{
           "id": 2,
           "name": "Development"
        }]
    }
]

someone to help?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire