鉴于一对一多态关系,无法检索数据

我有一个书籍表和一个图像表,将来我还将有一个博客表。这就是为什么我想在书籍、博客和图像表之间创建多态关系。但我的问题是,当我厌倦了从关系中检索图书图像 url 的数据时,home.blade.php我@foreach得到了以下结果:


Call to a member function getImage() on null (View: F:\xampp\htdocs\BookReader\resources\views\Main_pages\includes\Home\new_product.blade.php) 


代码如下:


home.blade.php


@extends('Main_pages.app')

@section('title','Home')

@section('content')

    @include('Main_pages.includes.Home.new_product')


    @include('Main_pages.includes.Home.testimonial')


    @include('Main_pages.includes.Home.popular_products')


    @include('Main_pages.includes.Home.news_letter')


    @include('Main_pages.includes.Home.blogs')


    @include('Main_pages.includes.Home.quick_view')

@endsection

new_product.blade.php


<section class="wn__product__area brown--color pt--80  pb--30">

<div class="container">

    <div class="row">

        <div class="col-lg-12">

            <div class="section__title text-center">

                <h2 class="title__be--2">New <span class="color--theme">Products</span></h2>

                <p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered lebmid alteration in some ledmid form</p>

            </div>

        </div>

    </div>

    <!-- Start Single Tab Content -->

    <div class="furniture--4 border--round arrows_style owl-carousel owl-theme row mt--50">

        @foreach($new_books as $book)

        <!-- Start Single Product -->}}

        <div class="product product__style--3">

            <div class="col-lg-3 col-md-4 col-sm-6 col-12">

                <div class="product__thumb">

                    <a class="first__img" href="single-product.html"><img src="{{$book->image->getImage()}}" alt="product image"></a>

                    <div class="hot__box">

                        <span class="hot-label">BEST SALLER</span>

                    </div>

                </div>


偶然的你
浏览 118回答 1
1回答

人到中年有点甜

这很明显。有一本没有任何图像的书。将img代码更改为:@isset ($book->image)&nbsp; &nbsp; <img src="{{$book->image->getImage()}}" alt="product image">@endisset或使用optional method和Null Coalesce Operator来获得默认图像:<img src="{{optional($book->image)->getImage() ?? 'default_image_path.png'}}" alt="product image">或者这个:@if (isset($book->image))&nbsp; &nbsp; <img src="{{$book->image->getImage()}}" alt="product image">@else&nbsp; &nbsp; <img src="default_image_path.png" alt="product image">@endif我希望这可以帮助你。
打开App,查看更多内容
随时随地看视频慕课网APP