dptsivmg82908 2016-06-25 09:47
浏览 31
已采纳

试图获得非对象的对象。 (Laravel)

I'm confused here. I've passed

$grade=Grade::all()->whereLoose('id',$gid);

from my controller. When I access it in my view like:

@foreach($grade as $grade)

{{$grade->grade_name}}


@endforeach

It works fine. But when i try to use it again in my table:

@foreach($grade as $grade)


<tr class="success">
    <td></td>
    <td><b>Balance</b></td>
    <td>{{$grade->fee_status}}</td>


@endforeach

It just throws Trying to get object of non object. What's the problem here? Can anyone help me?

  • 写回答

1条回答 默认 最新

  • dpd3447 2016-06-25 18:17
    关注

    You are reassigning $grade in your loop. It is now a single model. When you try to now iterate that you are iterating a single model which is not what you want to do (that will iterate the public properties of the object).

    This will avoid that issue:

    $grades = Grade::all()->whereLoose('id',$gid);
    
    // different name for the variable for the current iteration
    @foreach ($grades as $grade)
        ...
    @endforeach
    
    @foreach ($grades as $grade)
        ...
    @endforeach
    

    Watch the naming of variables.

    On a side note, I am not sure why you are getting all the grades to just find the one with 'id' equal to $gid. If the id field is unique there should only be one and you wouldn't need to retrieve a collection.

    $grade = Grade::find($gid);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?