Noel's avatar
Level 1

Undefined variable Laravel

Hi guys!!

I am m having this annoying problem. Can anyone give a hand to sort out it?

This is my controller

 class DashboardsController extends Controller
{
    public function indexA()
    {
        return view('dashboards.admin-dashboard');
    }

    public function indexS()
    {
        $id = Auth::user()->id;
        $courses = DB::table('registered__courses')->select('user_id')->where('user_id', '=', $id)->count();
        $posts = Post::all();

        return view('dashboards.student-dashboard', compact('id', 'courses', 'posts'));
    }

    public function indexT()
    {
        return view('dashboards.teacher-dashboard');
    }

This is a fragment of the blade view

 <div class="col-md-12">
      <div class="card">
        <div class="card-header">
          <h3 class="card-title">Posts</h3>
        </div>
        <div class="card-body">
          <div class="tab-content">
            <div class="active tab-pane" id="activity">
              <!-- Post -->
              <!--forEACH-->
              @foreach ($posts as $post)
              <div class="post">
                <div class="user-block">
                  <span class="username">
                    <a href="#">{{$post->title}} | {{$post->author}}</a>
                  </span>
                  <span class="description">{{optional($post->created_at)->format('d-m-Y')}}</span>
                </div>
                <!-- /.user-block -->
                <p>
                  {{$post->content}}
                </p>
              </div>
              @endforeach
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

And this is the routes

Route::group([
     'prefix' => 'dashboard',
 ], function () {
     Route::get('/admin', 'DashboardsController@indexA')
          ->name('dashboards.indexA');
     Route::get('/teacher', 'DashboardsController@indexT')
          ->name('dashboards.indexT');
     Route::get('/student', 'DashboardsController@indexS')
          ->name('dashboards.indexS');
 });

I tried to pass al the variable to the view and I always have the same problem. ("Undefined variable"). Any sugestions?

Thank you very much.

0 likes
36 replies
Noel's avatar
Level 1

Hi This is the content of the post (the paragraph inside). Thanks.

bugsysha's avatar

It probably says more than just a undefined variable. Post full error message.

Noel's avatar
Level 1

Undefined variable: posts (View: C:\laragon\www\hr-english\resources\views\dashboards\student-dashboard.blade.php)

jlrdw's avatar

Right after

$posts = Post::all();

add a

dd($post);

and show the results.

bugsysha's avatar

@jlrdw what ever that Post::all() returns it should be a collection which he can loop on.

Noel's avatar
Level 1
public function indexS()
    {
        $id = Auth::user()->id;
        $courses = DB::table('registered__courses')->select('user_id')->where('user_id', '=', $id)->count();
        $posts = Post::all();
        dd($posts);
        
        return view('dashboards.student-dashboard', compact('id', 'courses', 'posts'));
    }

After add dd ($posts), I am facing the same error. I restarted the server and cleared cache as well. The error Undefined variable: posts (View: C:\laragon\www\hr-english\resources\views\dashboards\student-dashboard.blade.php)

Noel's avatar
Level 1

bugsysha, no changes et all. Still same problem.

bugsysha's avatar

It can not say the same thing when you are not assigning it to a variable?

bugsysha's avatar

Comment everything in that method and just add

dd(Post::all());
Nakov's avatar

or share your web.php file please.. are you returning the same view from a different controller action?

Noel's avatar
Level 1
Route::group([
     'prefix' => 'dashboard',
 ], function () {
     Route::get('/admin', 'DashboardsController@indexA')
          ->name('dashboards.indexA');
     Route::get('/teacher', 'DashboardsController@indexT')
          ->name('dashboards.indexT');
     Route::get('/student', 'DashboardsController@indexS')
          ->name('dashboards.indexS');
 });

Hey Nakov. I am still remember you from last week, thanks. I am not really sure if I am doing well. I have one controller with different index method because I have got 3 roles and their dashboards show different information.

Noel's avatar
Level 1

If I use isset function the error disappear but values don´t appear on screen.

Nakov's avatar

@noel just make sure that in all your dashboards where you use the $posts variable you are passing it through. I don't know if you use one view or different for each endpoint. Put a dd with different value in every index action and check which one is called..

Noel's avatar
Level 1

Nakov, I have three different views, I did some tests and I do not have any problem to show the different views. The field role in the login redirect correctly to the right dashboard.

Nakov's avatar

and if you remove $posts from every view where you use it, you still get the error?

Try also naming the variable something else then just $posts in case you have a global view share which overrides the value..

Noel's avatar
Level 1

I am still getting the error. I delete from other views that are controller by the PostController and have the same problem in the dashboard.

I can pass any variable to the view, even I tried with a simple $name = "Noel" and it appears undefined variable.

Nakov's avatar

and your view is .blade.php right?

Run php artisan view:clear to remove cached views. Or just restart your server. I don't know what is the error exactly, doesn't make sense.. Comment out all the routes, and try just one, with a view and simple variable passed to the view..

bugsysha's avatar

If it wasn't blade file then he would not be able to use @foreach ($posts as $post).

Noel's avatar
Level 1

The three routes are blade.php I turned off the server , I ran php artisan view:clear and commented the routes belongs to admin and teacher to only work with the student route, and the same problem appear.

Nakov, In the beggining of the project I added a method called "authenticated" to the LoginController. Do you think it can be blocked the pass of the variables?

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */

    // protected $redirectTo = '/home';

    protected function authenticated($request)
    {
        if($request->user()->type == 'admin'){
            return redirect('/admin');
        } else if ($request->user()->type == 'teacher'){
            return redirect('/teacher');
        } else {
            return redirect('/student');
        }
    }

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

Nakov's avatar

@noel well if in some of those routes you use any of the variables that are not passed to the view, then it will throw an error, but it won't block it fir sure.. Just debug using breaking points such as the dd helper function, within each of the actions used by those routes. And make sure that everywhere you pass the necessary variables.

Noel's avatar
Level 1

Nakov, It is impossible to debug with the helper dd, it gives me the exception. I do not why. I have a serious problem, I need to present the project this week LOL.

Nakov's avatar

Well search in your whole project where do you use the posts variable or whatever variable throws the undefined exception and make sure you remove/comment it out everywhere, and start step by step to resolve your issue. It is even harder to debug not having your codebase :)

bugsysha's avatar

Delete everything from student-dashboard.blade.php and see if it happens again. But if it is happening inside controller methods that it has to be some shared variable so check your ServiceProviders.

Noel's avatar
Level 1

I delete the whole student-dashboard.blade.php and I tried to pass a simple variable and remains the problem. It is not something related to the $ post variable, it does not support any type of variable.

bugsysha's avatar

At this point I would clear all caches, remove vendor and do composer install. Also I would restart all services (php, database, web, etc...).

jlrdw's avatar

To add to what @bugsysha said I would get one part working at a time, make sure it's working before you get the next part working.

For example get $posts working make sure it's working then go to the next thing.

But good luck.

bugsysha's avatar

@jlrdw or even created new app and copy part by part from current one.

1 like
Noel's avatar
Level 1

Thanks guys for your time. I´ll try it.

Next

Please or to participate in this conversation.