samedi 4 août 2018

Get data from tables with one to one relation for API in Laravel

I'm working on my first Laravel project, and I want to create a REST Api for android application. In my system, I have two tables categories and images. Table images has column category_id wgich is a foreign key that references column id on category table

The categories table

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

... }

The images table

class CreateImagesTable extends Migration
{
    public function up()
    {
        Schema::create('images', function(Blueprint $table){
            $table->increments('id');
            $table->string('name')
            $table->integer('category_id')->unsigned();
            $table->foreign('category_id')
                ->references('id')
                ->on('categories')
                ->onDelete('cascade');
            $table->timestamps();
        });
    }
    ...
}

In the Images model class I did it:

class Images extends Model
{
    protected $fillable = ['name'];
    protected $hidden = array('created_at', 'updated_at');

    public function category(){
        $this->belongsTo('App\Category');
    }
}

I also created CategoryResource() class as:

class CategoryResource extends JsonResource

    {
          public function toArray($request)
        {
        return [
            'id'=> $this->id,
            'name' => $this->name,
        ];
        }
    }

So, I created a CategoryController to with the API methods, and configured the routes to access the corresponding function. The 'api/category/' url via GET is redirect to the index function of my controller, and the function is like that:

public function index()
{
    $categories = Category::get();
    return CategoryResource::collection($categories);
}

With this, I can get the categories table data, but I would like merge the users and images table, and get something like this as response:

[
   {
      'id': 1,
      'name': 'category_name',
      'image': 'image_name'
   }
]

How I can do this?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire