1

I have a query which show information from two tables in foreach loop on my blade view. This is the controller

public function details( $id ){

    $details = Item::find($id)->report;

    return view('details', compact('details'));
} 

On my view I have

@foreach($details as $itemDetails)
    ....
@endforeach 

Is it possible to show before foreach single variable from this query like?

{{ $details->id }}

@foreach($details as $itemDetails)
    ....
@endforeach 

I want to get the $id.

6
  • To get id outside loop because if I want it from the foreach loop I need to put foreach outside one div which then render multiple divs because of the loop... Commented Jan 19, 2017 at 5:51
  • can you share structure of sample of $details ? Commented Jan 19, 2017 at 5:52
  • 1
    Please show result of the {{ dd($details) }} Commented Jan 19, 2017 at 5:54
  • if you just want the id of first element then you can try something like collect($details)->first()->id Commented Jan 19, 2017 at 5:55
  • Thanks for the help. Bellow answer is working. I just trying to learn Laravel and some stuffs are kinda not clear yet. Commented Jan 19, 2017 at 5:56

1 Answer 1

1

Yes you can, try this:

$details[0]->id;

Try to understand the concept, every time you use model to get some data it returns an array of object like:

array(
    0 => stdClass Object,
    1 => stdClass Object,
    and so on
)

So to access the data we use foreach() loop or you can directly call the index as done above.

But if you are calling index directly then put a check for its existence using isset()

Sign up to request clarification or add additional context in comments.

5 Comments

its always recommended not to use hard-coded indexing as if can break if index is not available
@CerlinBoss in your case in the comment above isn't it the same or I'm wrong?
Yes it is highly recommended, and I have mentioned it in my updated answer
This will show error if $details has no records. Try to check the existence of the array with that index then access, try empty() or isset() functions for that.
@VLS : On accessing the property id, yes but the method first() would never throw error instead it will return false if no item found. So a simple if condition would be better

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.