php - how to pass data to a view without using if statement and foreach in the show file?
Get the solution ↓↓↓when I watched youtube Laravel From Scratch [Part 6] - Fetching Data With Eloquent , and I saw him pass data to view without using if statement and foreach, I has been tried but not working
public function show(todo $todo)
{
$todo=todo::find($todo);
return view('demo')->with('todo',$todo);
}
my view without if statement and foreach
@extends('layouts.app')
@section('content')
{{$todo->note}}
@endsection
my view when using if statement and foreach
@extends('layouts.app')
@section('content')
@if (count($todo) > 0)
@foreach ($todo as $item)
{{$item->note}}
@endforeach
@endif
@endsection
and I recievied an error
Property [note] does not exist on this collection instance
https://www.youtube.com/watch?v=emyIlJPxZr4&list=PLillGF-RfqbYhQsN5WMXy6VsDMKGadrJ-&index=6
Answer
Solution:
The reason the property doesn't exist is because the result is a collection instead of an array (found in the op comments)
So you're trying to getnote
from an collection that looks like this:
[
{
"id":1,
"note":"to do one",
"created_at":"2020-04-12 08:25:00",
"updated_at":"2020-04-13 07:20:54",
"description":"description for todo one"
}
]
When you call$todo->note
you're searching this line:
[
{ # <-- You're searching this line
"id":1,
"note":"to do one",
"created_at":"2020-04-12 08:25:00",
"updated_at":"2020-04-13 07:20:54",
"description":"description for todo one"
}
]
So your code is returning a collection instead of an array. An array would look like this:
{ # <-- Starts with open curly bracket instead of open square bracket
"id":1,
"note":"to do one",
"created_at":"2020-04-12 08:25:00",
"updated_at":"2020-04-13 07:20:54",
"description":"description for todo one"
}
You need to figure out why it's sending a collection.
From the look of your code, I find a potential issue with this:
public function show(todo $todo) # <- What is 'todo $todo'?
{
$todo=todo::find($todo);
return view('demo')->with('todo',$todo);
}
What istodo $todo
, are you calling the show function somewhere? By default Laravel sends that ID via the web route. So try updating it to this:
public function show($id) #<-- change this to '$id'
{
$todo = Todo::find($id); #<-- Change this to '$id'
return view('demo')->with('todo',$todo);
}
Let me know if that resolves it.
Edit: And you really need to fix your capitalization.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: property [id] does not exist on this collection instance.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.