IOS777
IOS777

Reputation: 35

laravel 5.6 fetching data from database to view

I'm facing an issue on understanding the content of the index function in the controller

I'm trying to get all the posts from my posts table into a view

my index function

public function index()
{
    $posts=\App\post::all();
    return view('MainViews.welcome',compact('posts'));
}

my view

   <div class="row">
    @foreach($posts as $post)
      <div class='col-md-8'>
        <div class="post"></div>
             h3>{{$post->subject}}</h3>
          <a href="#" class="btn btn-primary">read it</a>
          <p>
          </p>
        </div>
      @endforeach
     </div>

I'm getting Undefined variable error and highlighting @foreach

below is error highlighted

          <div class="row">
            18.    <?php $__currentLoopData = $posts; $__env->addLoop ($__currentLoopData); foreach($__currentLoopData as $posts):  $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
           19.          <div class='col-md-8'>
            20.            <div class="post"></div>
            21.              <h3><?php echo e($posts->subject); ?></h3>
            22.              <a href="#" class="btn btn-primary">read it</a>
             23.              <p>
             24.              </p>
              25.            </div>
               26.  <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
              27. 
               28.          </div>
                29.<?php $__env->stopSection(); ?>

Upvotes: 0

Views: 2640

Answers (1)

Ajay Kadoula
Ajay Kadoula

Reputation: 306

You Can simply use like this.

public function index()
{
    $posts=DB::select("select * from `users` where `email`='__'");
    return view('MainViews.welcome',['posts'=>$posts]);
}

The view

   <div class="row">
    @foreach($posts as $post)
     <div class='col-md-8'>
       <div class="post"></div>
         < h3>{{$post->subject}}</h3>`<br>
         <a href="#" class="btn btn-primary">read it</a>`<br>
       </div>
     @endforeach
    </div>

Upvotes: 1

Related Questions