0
votes

Hello I have two models Category and Product. The Category model has a table structure like so: "id, name" and the Product have: "id, name, category_id"

When I return all the products, I would like the category_id field replaced by the corresonding "name" value from the "categories" table.

Example:

Categories:

id    name
1     cloth
2     food

Products:

id    name      category_id
1     carrot    2
2     pants     1
3     shirt     1

Result

id    name      category_id
1     carrot    food
2     pants     cloth
3     shirt     cloth
2

2 Answers

1
votes

I think the Laravel way to do it and remain database agnostic would do the following. (FYI - I am using Laravel 5 namespacing.)

In your Product model have the proper category relationship defined, like so:

class Product extends Model {

     public function category(){
        return $this->hasOne('App\Category'); //Laravel 5 Namespacing included
    }

}

Then in your controller you would call:

$products = Product::with('category')->get();

And finally in your blade's foreach loop you can use this to access the category name:

@foreach($products as $product)
    $product->category->name
@endforeach

But you can always use Laravel's QueryBuilder Class to create manual joins also like so.

$products = Product::join('categories', 'categories.id', '=', 'products.category_id')
            ->selectRaw('products.id, products.name, categories.name as category_id')
            ->get();
0
votes

get all the products into a variable

$products = Product::all();

now use for loop on that variable

foreach ($products as $product)
{
    $id = $product->category_id;
    $category = Category::find($id)->name;
    $product->category_id = $category;
    $product->save();
}