Laravel获取数据并显示在bladehtml失败

Laravel get the data and display it in the blade html failed

我正在尝试从数据库中获取数据并将其显示在视图中

public function index()
{
    $messages = ProjectInterestedMessages::get();

    return view('dashboard/projects-interests', compact($messages));
}

风景

@foreach ($messages as $message)
    <h1>{{ $message->first_name }}</h1>
@endforeach

但是我收到这个错误

compact(): Argument #1 must be string or array of strings, Illuminate\Database\Eloquent\Collection given

PHP 方法 compact() 的语法有点棘手。我总是犯同样的错误。

变化:

return view('dashboard/projects-interests', compact($messages));

至:

return view('dashboard/projects-interests', compact('messages'));

compact() 查找变量的字符串表示形式。

您可以通过多种方式编写此内容。

在传递表示变量的字符串的地方使用 compact

public function index()
{
    $messages = ProjectInterestedMessages::get();

    return view('dashboard/projects-interests', compact('messages'));
}

使用 ->with

public function index()
{
    $messages = ProjectInterestedMessages::get();

    return view('dashboard/projects-interests')->with(['messages' => $messages]);
}

使用laravel魔法

public function index()
{
    $messages = ProjectInterestedMessages::get();

    return view('dashboard/projects-interests')->withMessages($messages);
}

就我个人而言,我更喜欢这种形式,因为它避免了无意义的变量

public function index()
{
    return view('dashboard/projects-interests')
        ->withMessages(ProjectInterestedMessages::get());
}

你不需要$

return 视图('dashboard/projects-interests', 压缩('messages'));