bin0
bin0

Reputation: 125

Getting a result from it's hasMany relationship in AngularJS and Laravel?

In Laravel, I have the API set up so /products shows all products in a JSON format, and that works great. Each product has, and can have many stocks. A stock is say the amount of the product we have, and the size of the product. So each product can have multiple stocks, such as they could have 4 of one size, 5 of another.

I've just hit a brick wall in my AngularJS where I'm trying to get all products where the product contains a stock (which is set up as a relationship in Laravel, hasMany, and the stocks table has a product_id column). I really cannot figure out how to do this in Angular. Any help towards the right direction would be great!

Upvotes: 0

Views: 379

Answers (1)

rfpdl
rfpdl

Reputation: 964

I am not really sure how to do it in AngularJS, but if you will do it in Laravel way

Define in your ProductsModel

public function stocks(){
    return $this->hasMany('StocksModel','product_id','id');
}

public function getProductsWithStocks(){
    return ProductsModel::with('stocks')->get();
}

and in your controller

$products = ProductsModel::getProductsWithStocks();

//return the view
return View::make('product.stock', ['products' => $products]);

Then in your product stock view

@foreach($products as $product)
Product Name:{{$product->name}}
@if($product->stocks)   //check if there is stock
    @foreach($product->stocks as $stock)
    Size {{$stock->size}} has {{$stock->quantity}} left
    @endforeach
@endif
@endforeach

Upvotes: 1

Related Questions