Skip to content
Advertisement

Laravel db table can’t throw variable from controller to page file

Hello I have problem with variable.

$data_news is undefined
Make the variable optional in the blade template. Replace {{ $data_news }} with {{ $data_news ?? '' }}

Controller take data from db and return view. Next in web.php Routing throw variable from Controller to page file

Controller Code

<?php
    namespace AppHttpControllers;
    
    use IlluminateSupportFacadesDB;
    use IlluminateHttpRequest;
    
    class NewsController extends Controller
    {
        public function home(){
            $data_news = DB::table('post')
            ->orderBy('id', 'DESC')
            ->limit(6)
            ->get()
            ->toArray();
    
            return view('Pages.home')->with('Pages', $data_news);
        }
    }

view page code

@foreach ($data_news as $news)
    <div class="col-md-4 col-xl-52"><img src="strony/assets/img/newspaper-solid.svg" style="width: 100px;">
        <p style="text-align: center;">{{ $news->title }}</p>
        <p style="text-align: left;"><br>{{ $news->text }}</p>
    </div>
@endforeach

And web.php Route

Route::resource(‘Pages/home’, ‘NewsController’);

How can I fix this problem

Advertisement

Answer

You pass it to the view as $Pages instead of $data_news.
The first parameter for the with function is the variable name

return view('Pages.home')->with('data_news', $data_news);

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement