Choy
Choy

Reputation: 482

how to use laravel eloquent to get and display data from other tables

I was using these codes in my controller to get all the data from my 2 tables and it works fine

$All = Customers::with('order')->paginate(10);

return response()->json([
    'code' => 0,
    'success' => true,
    'data' => $All
], 200);

Here is how I define the relationship between these 2 tables

class Customers extends Model
{
    public function order()
    {
        return $this->hasMany(Orders::class, 'customer_id', 'id');
    }
}

class Orders extends Model
{
    public function customers()
    {
        return $this->belongsTo(Customers::class, 'customer_id', 'id');
    }
}

enter image description here

Now my desire output is to hide the order id, order timestamps and change the customer_id to customer's name (the customer's name is not in my orders db table).

I'm using 'data' => DataResource::collection($All) in my controller and this is my DataResource

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

and of course the output is same with the image above.

My database structure:

Can anyone help me with that?

Upvotes: 1

Views: 1195

Answers (1)

Namoshek
Namoshek

Reputation: 6544

The answer is simple and basically a copy of the official documentation. You simply need to wrap your orders in an OrderResource as well.

// DataResource
public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
        'order' => OrderResource::collection($this->order)
    ];
}

// OrderResource
public function toArray($request)
{
    return [
        'items' => $this->items,
        'quantity' => $this->quantity
    ];
}

I don't really understand why you would want to include the customer_name in your orders when it is already present on the customers object one hierarchy above. But if you really want to add it, you should be able to do so with: 'customer_name' => $this->customers->name.

As a side note: you really should be more consistent with your naming. Why is the resource called DataResource when it is about Customers? Why is your model called Customers in plural form rather than Customer in singular, which is the convention (and more logical if you consider that one model represents one customer). Why is your belongsTo relation called customers() in plural when it returns one customer, while your hasMany relation is called order whereas it returns one or more orders?

Upvotes: 1

Related Questions