C
C
codeschemer2017-01-19 05:37:15
Laravel
codeschemer, 2017-01-19 05:37:15

How to check instanceOf in blade?

How to make a check in the View similar to that for the controller

foreach($collection as $object){
    if($object instanceof ModelName1){ //code goes here.. }
    elseif($object instanceof ModelName2){ //code goes here.. }
    else($object instanceof ModelName3){ //code goes here.. }
 }

Laravel 5.1.
The Laravel way is especially interested in the style of the solution, without <? php, succinctly
. I don’t want to pass an additional array in which the Model ID will be, but so far I have to.
Options for 5.2, 5.3, or 4.x are also interesting, maybe it will be useful to someone.
Andrzej Wielski suggested
@if(count($collection))
    @foreach($collection as $object)
        @if($object instanceof ModelName1)
              //
        @elseif($object instanceof ModelName2)
              //
        @elseif($object instanceof ModelName2)
              //
        @endif
    @endforeach
@endif

however, in that case,
dd($object); //ModelName1
dd($object instanceof ModelName1); //false

Original code (part)
view
@if(count($newPreorderDetails))
 @foreach($newPreorderDetails as $newPreorderDetail)
  @if($newPreorderDetail instanceof BaseDetail)
   go go go
  @endif
 @endforeach
@endif

Model app\BaseDetail.php
class BaseDetail extends Model
{      
// конструкторы, связи, группы и много всего
}

And my dumps
dd($newPreorderDetail);

BaseDetail {#267 ▼
  #table: "base_detail"
  #guarded: []
  #connection: null
  #primaryKey: "id"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: array:19 [▶]
  #original: array:19 [▶]
  #relations: []
  #hidden: []
  #visible: []
  #appends: []
  #fillable: []
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: true
  +wasRecentlyCreated: false
}

and
dd($newPreorderDetail instanceof BaseDetail);

false

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry, 2017-01-19
@codeschemer

Show original code. When checking, do you indicate the namespace of the model?

D
Dmitry Evgrafovich, 2017-01-19
@Tantacula

Does it make sense to complicate the code and not use standard blade constructs @if и @foreach?

A
Andrzej Wielski, 2017-01-19
@wielski

@if(count($collection))
    @foreach($collection as $object)
        @if($object instanceof ModelName1)
              //
        @elseif($object instanceof ModelName2)
              //
        @elseif($object instanceof ModelName2)
              //
        @endif
    @endforeach
@endif

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question