Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Glens's avatar
Level 1

Undefined Variable - i've tried for over a week!

I know i'm a beginner when it comes to Laravel, but i've been googling endlessly for over a week to try and figure out what i'm doing wrong. I can't even seem to copy and paste to get it right!

Basically I have my controller:

<?php
 
namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
 
class TestResultsController extends Controller
{
    /**
     * Show a list of all of the application's pol test results.
     */
    public function testresults()
    {
       // $testresults ='empty';
     $testresults =DB::select('select * from tests');
      return view('tests',compact('testresults'));
 
        
    }
}

I have my Route:

Route::get('/tests', [TestResultsController::class, 'testresults']);

and then in my blade file called tests.blade.php

                     {{$testsresults}}   
                  
         </span>

I figure the issue is in the controller and i've tried so many variations i'm now totally lost. It's laravel 11. It's annoying me because I have used Laravel last year even if I copy bits from that I can't get it to work! The rest of the pages work just not the ones I try and call variables in.

Thank you for your help!

0 likes
29 replies
jlrdw's avatar

What do you get if you:

@php dd($testresults); @endphp
Snapey's avatar

@jlrdw probably undefined variable, as it is $testresults

Jsanwo64's avatar

noticed this typo

 $testresults =DB::select('select * from tests');

it should be

 $testresults = DB::select('select * from tests');
Glens's avatar
Level 1

@jlrdw Thank you for your suggestions ErrorException Undefined variable $testresults

I'm sure the problem is in the controller. looking back at my previous laravel site it looks like i just did the database work in the views which isn't realy proper so i must have had the same issues!

Snapey's avatar

@Glens im not sure you are even calling the controller, and you are displaying the view by some other route.

You really need to take a step back and do some training so that you have the basic principles

martinbean's avatar

@glens It’s not working because testsresults != testresult (notice the extra “s” after “test” in your view).

Glens's avatar
Level 1

@martinbean it's not the issue, i've been through the code that many times and so many variations i think i just need to delete the whole site and start fresh.

when i see the list of routes via artisan the Test Results controller is there, but the variable no matter if its a string of an array does not get passed to any view if i change it. so i need to figure out where i'm going wrong and read up on it... a lot! :D

Snapey's avatar

@Glens you are overlooking something obvious. Can you post your entire web.php?

Glens's avatar
Level 1

@Snapey PoolTestResultsController.php

<?php
 
namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
 
class PoolTestResultsController extends Controller
{
  
    /**
     * Show a list of all of the application's pol test results.
     */
    public function pooltestresults()
    {
       // $testresults ='empty';
    $pooltestresults = DB::select('select * from pool_tests');
      return view('pooltests',compact('pooltestresults'));
        
    }
}

web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\RoutingController;
use App\Http\Controllers\PoolTestResultsController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

require __DIR__ . '/auth.php';

Route::group(['prefix' => '/', 'middleware' => 'auth'], function () {
    Route::get('', [RoutingController::class, 'index'])->name('root');
    Route::get('/home', fn()=>view('dashboards.index'))->name('home');
    Route::get('{first}/{second}/{third}', [RoutingController::class, 'thirdLevel'])->name('third');
    Route::get('{first}/{second}', [RoutingController::class, 'secondLevel'])->name('second');
    Route::get('{any}', [RoutingController::class, 'root'])->name('any');
});

Route::get('/pooltests', [PoolTestResultsController::class, 'pooltestresults' ] )->name('pooltests');

excerpt from pooltests.blade.php which is in the views directory. [i will create the for each loop etc once i know the variable is being passed]

                                <h4 class="mb-3">
                                    <span class="ti ti-square-rounded-arrow-down text-success me-1"></span>
                                    <span>
                     {{$pooltestresults}}   
                  
         </span>
                                </h4>```

i really do appreciate your help. i have spent a while trying to learn but as you say i'm probably missing something obvious now because i've tried so hard
Glens's avatar
Level 1

@Snapey route:ist shows:

  GET|HEAD   pooltests . pooltests › PoolTestResultsController@pooltestresults

so i assume it's trying to use it

Tray2's avatar
Tray2
Best Answer
Level 73

@Glens Like @snapey says, your controller will never ever be hit.

The order or the routes is the key here.

Take a look here, at a simplification of your routes.

Route::get('/{any}', [RoutingController::class, 'root'])->name('any);
Route::get('/pooltests', [PoolTestResultsController::class, 'pooltestresults' ] )->name('pooltests');

The first one will always be the one matching, it means /whatever-you-put-here-will-match-including-pooltests

Of course if you are not logged in then it hits the correct route, or at least should.

You need to be careful with the order of the routes when it comes to using wildcards in them.

So this

Route::group(['prefix' => '/', 'middleware' => 'auth'], function () {
    Route::get('', [RoutingController::class, 'index'])->name('root');
    Route::get('/home', fn()=>view('dashboards.index'))->name('home');
    Route::get('{first}/{second}/{third}', [RoutingController::class, 'thirdLevel'])->name('third');
    Route::get('{first}/{second}', [RoutingController::class, 'secondLevel'])->name('second');
    Route::get('{any}', [RoutingController::class, 'root'])->name('any');
});

Route::get('/pooltests', [PoolTestResultsController::class, 'pooltestresults' ] )->name('pooltests');

Should be this, that way it will hit the pooltests and not the any route.

Route::get('/pooltests', [PoolTestResultsController::class, 'pooltestresults' ] )->name('pooltests');

Route::group(['prefix' => '/', 'middleware' => 'auth'], function () {
    Route::get('', [RoutingController::class, 'index'])->name('root');
    Route::get('/home', fn()=>view('dashboards.index'))->name('home');
    Route::get('{first}/{second}/{third}', [RoutingController::class, 'thirdLevel'])->name('third');
    Route::get('{first}/{second}', [RoutingController::class, 'secondLevel'])->name('second');
    Route::get('{any}', [RoutingController::class, 'root'])->name('any');
});

Then of course you have some other errors in your routes file, and you are using a very bad practice when it comes to how you define your routes and controllers.

I highly recommend starting here before you do anything else.

https://laracasts.com/series/30-days-to-learn-laravel-11

1 like
Glens's avatar
Level 1

@Tray2 thank you, i've got it sorted now! I guess that's one of the problems with using templates to get started, i totally missed the "any" route. a simple re-ordering of routes and DB statements and all is well.

I really appreciate everyone's input thank you!

tykus's avatar

@glens do you have another Route / Controller that is returning the tests Blade template, where the $testresults variable is not being passed to the View?

Glens's avatar
Level 1

@tykus i just looked only the one is, i've cleared caches as well.

it's bound to be something simple but im just blind to it now

Snapey's avatar

You will never reach pooltests based on your web.php file.

Glens's avatar
Level 1

@Snapey thank you for the guidance. I'm at a total loss now. looking at youtube turorials i can't see the difference between my routes/web.php files lol. I maybe need to take a few days off it and come back to it fresh I've honestly spent so much time trying to figure this out which should be straight forward! I can do pretty much everything else but this step to progress with my project has me flummoxed

LucaPuddu's avatar

@glens make sure that everything is being called correctly.

In the controller method:

public function testresults()
{
     $testresults =DB::select('select * from tests')->get(); // note the ->get() here

     dd($testresults); // is this being shown?

     return view('tests',compact('testresults'));
}

If you can see $testresults, then move to the view:

tests.blade.php

{{$testresults}}

You should now see the output correctly (as a json string)

Glens's avatar
Level 1

@LucaPuddu thank you, i tried this and still get the same variable not defined error. if i remove the variable the page works and i don;'t see any data dump

Shivamyadav's avatar

@Glens 8887926611 you can whatsapp me right now I will help you remotely with anydesk

Jsanwo64's avatar

@LucaPuddu

Am i failing to understand that

 $testresults =DB::select('select * from tests')->get(); // note the ->get() here

contains a typo as corrected earlier

Shivamyadav's avatar

@jsanwo64 sorry man ♂️ but select method doesn't provide or return a query builder. Where as get() is used for retrieving the data an can be chained only with eloquent query builder

Jsanwo64's avatar

@shivamyadav i meant

$testresults =DB::select('select * from tests')->get(); // note the ->get() here

should be

$testresults = DB::select('select * from tests')->get(); // note the ->get() here
Snapey's avatar

@jsanwo64 no, should be

    DB:table('tests')->get();

But it is irrelevant since this controller is never called

1 like
Jsanwo64's avatar

@Snapey Thanks.. So True, i actually was still confused at the rest of the code. The =DB was what caught my attention pretty fast.

1 like

Please or to participate in this conversation.