Laravel 6 -> Retrieving All Records -> "undefined constant" WHY?

Bruce Gust
Bruce Gust used Ask the Experts™
on
Ninjas!

I'm using Laravel 6 which is becoming more and more significant as I'm working through a Laravel 5 tutorial.

In any event, here's my Controller:

	public function index()
    {
        //get pages
		$pages = Page::all();
		return view('admin/listPages', compact($pages));
    }

Open in new window


...and here's my View:

@foreach($pages as $page)
								<tr>
									<td>{{ $page->name }}</td>
								</tr>
							@endforeach

Open in new window


I get an error that says:

Undefined variable: pages (View: C:\wamp64\www\new_nomas\resources\views\admin\listPages.blade.php)

I've played with a couple of different things, including this on my Controller

public function index()
    {
        //get pages
		$pages = Page::all();
		return view('admin/listPages', [b]compact(pages))[/b];
    }:

Open in new window


And in that scenario, I get this error (pertaining to my Controller):

Use of undefined constant pages - assumed 'pages' (this will throw an Error in a future version of PHP)

What am I missing?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Evening Bruce,

When you pass data to a view, you need to pass an array - the key becomes the variable in the View, so if you do this:

return view('myPage', [ 'firstName' => 'Chris'] );

Then the view has access to a variable called $firstName:

<h1> {{ $firstName }} </h1>

In your case, you need to pass it something like this:

$pages = Page::all();
return view('admin/listPages', [ 'pages' => $pages ]);

Now you'll have a $pages variable in your view that you can loop through

The reason you're getting the undefined constant is because you're trying to access pages and not $pages
Bruce GustPHP Developer

Author

Commented:
Hey, Chris!

Does "compact" not do what you have referenced as far as ['pages' => $pages]?

I'm asking that because that's what the tutorial appears to advocate, and yet I get the error that I mentioned.

Here's what I'm attempting to digest...

screenshot of tutorial
So, there's that.

Now, when I implement your solution, I get closer to where I need to be, but I'm still coming up short.

Here's my Controller:

public function index()
    {
        //get pages
		$pages = Page::all();
		return view('admin/listPages', ['pages'=>$pages]);
    }

Open in new window


Here's my View:

<table class="table">
						<?php var_dump($pages); ?>
							@foreach($pages as $page)
								<tr>
									<td>{{ $page->name }}</td>
								</tr>
							@endforeach				
						</table>

Open in new window


And here's what the page looks like:

empty list
So it would seem that the page "senses" data, but I'm not able to print anything based on the syntax I'm currently using.

One more thing...

When I do a var_dump here:

code]<table class="table">
                                    <?php var_dump($pages); ?>
                                          @foreach($pages as $page)
                                                <tr>
                                                      <td>{{ $page->name }}</td>
                                                </tr>
                                          @endforeach                        
                                    </table>[/code]

I get this:

C:\wamp64\www\new_nomas\storage\framework\views\0798441722c872e8f128792763c11a29231416be.php:26:
object(Illuminate\Database\Eloquent\Collection)[296]
  protected 'items' => 
    array (size=3)
      0 => 
        object(App\Page)[297]
          protected 'fillable' => 
            array (size=3)
              ...
          protected 'connection' => string 'mysql' (length=5)
          protected 'table' => string 'pages' (length=5)
          protected 'primaryKey' => string 'id' (length=2)
          protected 'keyType' => string 'int' (length=3)
          public 'incrementing' => boolean true
          protected 'with' => 
            array (size=0)
              ...
          protected 'withCount' => 
            array (size=0)
              ...
          protected 'perPage' => int 15
          public 'exists' => boolean true
          public 'wasRecentlyCreated' => boolean false
          protected 'attributes' => 
            array (size=6)
              ...
          protected 'original' => 
            array (size=6)
              ...
          protected 'changes' => 
            array (size=0)
              ...
          protected 'casts' => 
            array (size=0)
              ...
          protected 'dates' => 
            array (size=0)
              ...
          protected 'dateFormat' => null
          protected 'appends' => 
            array (size=0)
              ...
          protected 'dispatchesEvents' => 
            array (size=0)
              ...
          protected 'observables' => 
            array (size=0)
              ...
          protected 'relations' => 
            array (size=0)
              ...
          protected 'touches' => 
            array (size=0)
              ...
          public 'timestamps' => boolean true
          protected 'hidden' => 
            array (size=0)
              ...
          protected 'visible' => 
            array (size=0)
              ...
          protected 'guarded' => 
            array (size=1)
              ...
      1 => 
        object(App\Page)[298]
          protected 'fillable' => 
            array (size=3)
              ...
          protected 'connection' => string 'mysql' (length=5)
          protected 'table' => string 'pages' (length=5)
          protected 'primaryKey' => string 'id' (length=2)
          protected 'keyType' => string 'int' (length=3)
          public 'incrementing' => boolean true
          protected 'with' => 
            array (size=0)
              ...
          protected 'withCount' => 
            array (size=0)
              ...
          protected 'perPage' => int 15
          public 'exists' => boolean true
          public 'wasRecentlyCreated' => boolean false
          protected 'attributes' => 
            array (size=6)
              ...
          protected 'original' => 
            array (size=6)
              ...
          protected 'changes' => 
            array (size=0)
              ...
          protected 'casts' => 
            array (size=0)
              ...
          protected 'dates' => 
            array (size=0)
              ...
          protected 'dateFormat' => null
          protected 'appends' => 
            array (size=0)
              ...
          protected 'dispatchesEvents' => 
            array (size=0)
              ...
          protected 'observables' => 
            array (size=0)
              ...
          protected 'relations' => 
            array (size=0)
              ...
          protected 'touches' => 
            array (size=0)
              ...
          public 'timestamps' => boolean true
          protected 'hidden' => 
            array (size=0)
              ...
          protected 'visible' => 
            array (size=0)
              ...
          protected 'guarded' => 
            array (size=1)
              ...
      2 => 
        object(App\Page)[299]
          protected 'fillable' => 
            array (size=3)
              ...
          protected 'connection' => string 'mysql' (length=5)
          protected 'table' => string 'pages' (length=5)
          protected 'primaryKey' => string 'id' (length=2)
          protected 'keyType' => string 'int' (length=3)
          public 'incrementing' => boolean true
          protected 'with' => 
            array (size=0)
              ...
          protected 'withCount' => 
            array (size=0)
              ...
          protected 'perPage' => int 15
          public 'exists' => boolean true
          public 'wasRecentlyCreated' => boolean false
          protected 'attributes' => 
            array (size=6)
              ...
          protected 'original' => 
            array (size=6)
              ...
          protected 'changes' => 
            array (size=0)
              ...
          protected 'casts' => 
            array (size=0)
              ...
          protected 'dates' => 
            array (size=0)
              ...
          protected 'dateFormat' => null
          protected 'appends' => 
            array (size=0)
              ...
          protected 'dispatchesEvents' => 
            array (size=0)
              ...
          protected 'observables' => 
            array (size=0)
              ...
          protected 'relations' => 
            array (size=0)
              ...
          protected 'touches' => 
            array (size=0)
              ...
          public 'timestamps' => boolean true
          protected 'hidden' => 
            array (size=0)
              ...
          protected 'visible' => 
            array (size=0)
              ...
          protected 'guarded' => 
            array (size=1)
              ...

Open in new window


I'm looking for "title" or "body," and I don't see squat.

What do you think?
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Right,

When you call compact, you need to pass it a string matching the name of a variable. In your original code, you're passing in a variable.

You had this:

$pages = Page::all();
return view('admin/listPages', compact($pages));

What you should have had was this:

$pages = Page::all();
return view('admin/listPages', compact('pages')); //notice we're passing in a string.

This will achieve the same results as passing in an array - the compact just creates that for you.

Regarding the var_dump - the $pages variable is not just a collection of simple $page objects (name, description etc). It's a collection of Eloquent models, so when you var_dump $pages, you're var_dumping the whole collection, including all the additional members of Eloquent models. When you iterate over a collection in Blade, it actually iterates over the items property of the collection, which is why you can echo out the individual properties.

Not sure why you're not getting any info. Try a simple alternative in your view file:

@foreach($pages as $page)
    <p>{{ $page }}</p>
@endforeach

Open in new window

Learn Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Bruce GustPHP Developer

Author

Commented:
Chris!

I went back to my notes and I figured it out.

Could you tell me WHY this works?

public function index()
    {
        //get pages
      $pages = Page::all();
      //return view('admin/listPages', ['pages'=>$pages]);
      return view('admin/listPages', compact('pages'));
    }

And then on my View, I do this:

@foreach($pages as $page)
                                                <tr>
                                                      <td>{{ $page->title }}</td>
                                                </tr>
                                          @endforeach                        

...and I'm gold!

But what's significant about compact('pages')? Why the single quote?
Bruce GustPHP Developer

Author

Commented:
I think you answered my question as I was typing it.
Bruce GustPHP Developer

Author

Commented:
Perfect!

Thank you, sir!

And listen, I've going to have more questions. It's amazing how a tutorial is one thing, but building something completely on your own is another.

Rock on!
Bruce GustPHP Developer

Author

Commented:
As always, a very valuable resource!
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
No worries Bruce.

It's a never ending learning process, but by building your own application, the leaning process will stick more than reading tutorials - it may just take a little while (and a lot of frustrating). Keep at it :)

FYI - in the following, $data1 and $data2 are exactly the same thing, so you can use either in your call to view :)

$pages = Page::all();
$data1 = ['pages' => $pages];
$data2 = compact('pages');

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial