0

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(); ?>

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

4 Comments

also, check the name of the view same in index
Undefined variable: posts (View: C:\Users\amaar\Desktop\Blog\resources\views\MainViews\welcome.blade.php) @Ajay
make sure the name of view same in index function.
also sure that these file included with your index function <br> namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use DB;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.