Search code examples
laravelvue.jslumen

retrieve forign key first value in laravel


I have three tables Products, Category and Images. Category and Image tables have relationship with Product table. when I have use $all_product = Product::with('category','image')->get();product information category information and image information are display successfully want i want is Question : how to retrieve the image arrays first value?

"all_objects": [
    {
        "id": 1,
        "name": "samsung",
        "price": "2000",
        "category_id": 1,
        "created_at": "2020-02-17 13:27:24",
        "updated_at": "2020-02-17 13:27:24",
        "category": {
            "id": 1,
            "category_name": "android",
            "created_at": "2020-02-17 13:26:42",
            "updated_at": "2020-02-17 13:26:42"
        },
        "image": [
            {
                "id": 1,
                "image_name": "image_787.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:25",
                "updated_at": "2020-02-17 13:27:25"
            },
            {
                "id": 2,
                "image_name": "image_539.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:25",
                "updated_at": "2020-02-17 13:27:25"
            },
            {
                "id": 3,
                "image_name": "image_606.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:25",
                "updated_at": "2020-02-17 13:27:25"
            },
            {
                "id": 4,
                "image_name": "image_102.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:26",
                "updated_at": "2020-02-17 13:27:26"
            }
        ]
    },

Solution

  • The get() method returns an instance of Illuminate\Database\Eloquent\Collection so you can use all available methods on Laravel collections.

    To get your first image:

    $all_product = Product::with('category','image')->get();
    
    foreach ($all_product as $product) {
        $first_image = optional($product->image)->first();
    
        // do whatever you want with the $first_image
    }
    

    The optional() method is used in a case product had no images (i.e $product->images was null).