doulin2555 2019-01-06 11:02
浏览 98
已采纳

ErrorException未定义的变量Laravel

Hey guys I just started learning how to use Laravel and when I tried running the code below I get:

Undefined variable error

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <ul>
        @foreach ($tasks as $task)
            <li>{{ $task->Todo }}</li>
        @endforeach
    </ul>
</body>
</html>

this is the code used in the web.php file:

web.php

Route::get('/tasks', function () {
        $tasks = DB::table('tasks')->get();
    //return $tasks;
        return view('welcome',compact($tasks));
    });

I discovered that if I use the $GLOBALS['variable']; to replace the $tasks variable in both files it works.

But in the example video from laracasts they didn't make use of the $GLOBALS['variable'];

This is the error I get:

"Undefined variable: tasks (View: C:\Users\Friday\Documents\Documentations\laraprojects\BrainGearesources\views\welcome.blade.php)"

  • 写回答

2条回答 默认 最新

  • douyuan6490 2019-01-06 11:27
    关注

    You need to pass the variable name in the compact() helper (as @utdev said). You can read more about this here. So:

    return view('welcome', compact('tasks'));
    

    Another option is to send the variable to the view like this:

    return view('welcome')->with('tasks', $tasks);
    

    or even "sugared" (equivalent to the last one):

    return view('welcome')->withTasks($tasks);
    

    To know more about this, check the Passing data to views section of the documentation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部