Skip to content
Advertisement

Undefined variable: posts (View: C:UsersBWBDocumentsLaravelrestravelsresourcesviewsprofile.blade.php)

So I’m working on a blog website and I want to associate users with certain posts and posts with certain users. So I have a profile page that displays the current logged in user’s info but doesn’t pass the posts related to the user. I dont know if its my model relations that are wrong but i keep getting the posts not defined error. Here is my ProfileController

<?php

namespace AppHttpControllers;

use AppReviews;

use IlluminateFoundationAuthUser;

use IlluminateHttpRequest;

class ProfileController extends Controller
{

    public function index()
    {
        $user_id=auth()->user()->id;
        $users = User::find($user_id);
        $user = User::where('id', $user_id)->get();
        $post= $users->posts;

//        $user=Auth::user();
//
//        $post= $user->posts;


        return view('profile')->with(['users' =>$user ],['posts' => $post ]);
    }
}


Here is my Post model’s user method

  public function user(){
        return $this->belongsTo('AppUser');

    }

Here is my User model’s posts method

 public function posts(){
        return $this->hasMany('AppPost');

    }

Here is how i output it in the view

 @foreach($users as $user)
                    <div class="card-body">
                        <h5 class="card-title">{{ $user->fname}}<br>{{ $user->lname}}</h5>
                        <h5 class="card-text">Email</h5>
                        <p class="h6">{{ $user->email}}</p>
                        <h5 class="card-text">Address</h5>
                        <p class="h6">Phenom Estate<br>{{$user->city}}, Kenya</p>
                        <h5 class="card-text">Award</h5>
                        <p class="h6">Globe Trotter</p>
                        <a href="#" class="btn btn-primary btn-block">Edit Profile</a>
                    </div>
                    @endforeach
                    @if (count($posts)>0)


                    @foreach($posts as $post)
                        <div class="well row">
                            <div class="col-md-4">
                                <img style="width: 100%; height: 300px" src="/storage/cover_images/{{$post->cover_image}}" alt="">
                            </div>
                            <div class="col-md-8">
                                <h3> <a href="/posts/{{$post->id}}">{{$post->title}}</a></h3>
                                <h3>{{$post->created_at}}</h3>
                            </div>
                        </div>
                    @endforeach
                    @endif

Advertisement

Answer

You have an error in the view return. It should be:

return view('profile', ['users' => $user, 'posts' => $post]);

Please see: https://laravel.com/docs/7.x/blade#displaying-data

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