N
N
Nubbb2021-02-15 11:39:53
Laravel
Nubbb, 2021-02-15 11:39:53

How to return the store data and the last 3 posts of the store correctly?

there is a Shop model - id, name, logo

class Shop extends Model
{
    use HasFactory;

    protected $table = 'shops';


    public function latestPost()
    {
        $this->hasMany(ShopPost::class);
    }
}


ShopPost shop news model - id, shop_id, title

Did I correctly organize the display of shop data and news, if I want to display, for example, the last 5 products of the shop also through the link?

public function getShopInfo(int $shopId){
        $shop = Shop::find($shopId);

        if (!$shop) return response()->json(['error' => true, 'message' => 'Shop not found'], 404);

        return response()->json([
            'error' => false,
            'shop' => $shop,
            'posts' => $shop->posts()->latest()->take(3)->get()
        ], 200);
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kuznetsov, 2021-02-15
@Nubbb

Before $this->hasMany write return!
You even said it in a mistake!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question