I am trying to get data from the database and simply display it in the view
public function index()
{
$messages = ProjectInterestedMessages::get();
return view('dashboard/projects-interests', compact($messages));
}
The view
@foreach ($messages as $message)
<h1>{{ $message->first_name }}</h1>
@endforeach
But I am getting this error
compact(): Argument #1 must be string or array of strings, Illuminate\Database\Eloquent\Collection given
CodePudding user response:
The PHP method compact()
is a little tricky with its syntax. I make this same mistake all the time.
Change:
return view('dashboard/projects-interests', compact($messages));
to:
return view('dashboard/projects-interests', compact('messages'));
compact()
looks for a string representation of the variable.
CodePudding user response:
There are multiple ways you could write this.
using compact where you pass strings representing the variable
public function index()
{
$messages = ProjectInterestedMessages::get();
return view('dashboard/projects-interests', compact('messages'));
}
using ->with
public function index()
{
$messages = ProjectInterestedMessages::get();
return view('dashboard/projects-interests')->with(['messages' => $messages]);
}
With using laravel magic
public function index()
{
$messages = ProjectInterestedMessages::get();
return view('dashboard/projects-interests')->withMessages($messages);
}
Personally, I prefer this form as it avoids pointless variables
public function index()
{
return view('dashboard/projects-interests')
->withMessages(ProjectInterestedMessages::get());
}
CodePudding user response:
You don't need $
return view('dashboard/projects-interests', compact('messages'));