简体   繁体   中英

How to pass database value from controller to dashboard in Laravel 9

I have a method in my controller, PostsController:

public function index()
{
    $post = Posts::where('id', '1')->get(['post']);
    return $post;
}

web.php

Route::get('test', [PostsController::class, 'index']);

into test.blade.php in my views folder, and show it with

{{ $post }}

This works perfectly. However, when I try to do the exact same thing to the dashboard.blade.php, I get

Undefined variable $post

When trying to get this data on dashboard, I use this in app.php instead.

Route::get('dashboard', [PostsController::class, 'index']);

I was expecting to get the same data on the dashboard as in test.blade.php, but it cannot find the variable anymore as soon as I change the view in the route. What am I doing wrong?

try this

return view('test', [
    'post' => Posts::where('id', '1')->get()
]);

and if your test.blade is not directly inside the views folder you need to specify the folder like that: view('folderName.test', ...)

and for more information, you can check the documentation https://laravel.com/docs/9.x/controllers

I was just being dumb - view wasn't a view at all.

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