简体   繁体   中英

variables not passing to view in laravel from controller

Variables not passing to views in laravel project from the controller. getting Undefined variable: title error.

function index()
{

    $data = array(
        'title' => 'Font Awesome & Material Design Icons',
        'description' => 'Create your project with Font Awesome & Material Design Icons',
        'seo_keywords' => 'Create your project with Font Awesome & Material Design Icons',
        'data' => DB::table('fontawesomeicons')->orderBy('id', 'asc')->paginate(50),
    );   

    // $data = DB::table('fontawesomeicons')->orderBy('id', 'asc')->paginate(50);
    return view('pagination', compact('data'));
}

The compact function will create an array with data as the only key and the array as its value. This is not what you should do, you need an array that directly contains the variables you need in your view.

So you can just pass the data array as the second attribute for the view() function.

return view('pagination', $data);

Or if you really want to send the entire $data array as a whole variable, you have to use the array indexes in your blade views:

{{ $data['title'] }}

Try

return view('pagination')->with(compact('data'));

Or try

$title = 'Font Awesome & Material Design Icons';
$description = 'Create your project with Font Awesome & Material Design Icons';
$seo_keywords = 'Create your project with Font Awesome & Material Design Icons';
$data = DB::table('fontawesomeicons')->orderBy('id', 'asc')->paginate(50);

return view('pagination',compac(['title','description','seo_keywords','data']));

compact('data') returns array like this: ['data' => $data]

So return view('pagination', compact('data')); code is equivalent to this:

return view('pagination', ['data' => $data]);

And you have access to controller variable like this: $data['title'] , $data['description'] ... You shold pass data in view instead of compact('data') :

return view('pagination', $data);

Or you can use

return view('pagination', compact('data')['data']);

But this doesn't makes sense

you could try something like this:

function index()
{

    $data['data'] = array(
        'title' => 'Font Awesome & Material Design Icons',
        'description' => 'Create your project with Font Awesome & Material Design Icons',
        'seo_keywords' => 'Create your project with Font Awesome & Material Design Icons',
        'data' => DB::table('fontawesomeicons')->orderBy('id', 'asc')->paginate(50),
    );   

    // $data = DB::table('fontawesomeicons')->orderBy('id', 'asc')->paginate(50);
    return view('pagination', $data);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM