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

Kish77's avatar

compact(): undefined variable

Good day, guys! I am trying to return a view with some data passed to it in compact() but for some reason, compact() is saying undefined variable despite showing me the variable value! I am a passing a value via an anchor tag to a controller function that accepts the passed variable as an argument.

My anchor tag:

    <a class="btn btn-primary" href="{{url('/invoice/'.$orders)}}" target="_blank" value="{{$orders}}">View</a>

Route:

    Route::get('/invoice/{orders}',  'Company\InvoicesController@viewOrder');

Controller:

    public function viewOrder($orders){

     //get other stuff here

     return view('company.invoice', compact(['order_totals'=>$order_totals, 
                           'order_items'=>$order_items, 
                           'orderNum'=> $orders,
                            'other_fee'=>$this->other_fee,
                            'gct'=>$this->gct,
                            'processing_fee'=>$this->processing_fee,
                            'bank_fee'=>$this->bank_fee,
                            'title'=>'Invoice']));
   }

Error says: compact(): Undefined variable: 111-2 (the order passed in by anchor tag)

0 likes
5 replies
Kish77's avatar

I solved it. I just returned the array of variables without using compact().

deansatch's avatar

@KISH77 - Just for your future reference if you want to use compact, you should use it like this:


return view('company.invoice')
    ->compact(
    'order_totals', 
    'order_items', 
    'orderNum',  // so in blade this would be {{$orderNum}} not {{$orders}}
    'other_fee',
    'gct',
    'processing_fee',
    'bank_fee',
    'Invoice' // in blade this would be {{$Invoice}} not {{$title}}
);

The idea is, if your variables are named the same as what you want them to be in your view you can use compact() to cut your code down. So in your case just the title and orderNum would either need variables renaming in your controller, or in your view, whichever you prefer.

gitwithravish's avatar

The issue could be with php versions as well. I degraded my php version from 7.4 to 7.1 and it got resolved !

tousifkhan's avatar

This is definitely updated PHP issue, you will not face this issue on php 7.2

Snapey's avatar

@tousifkhan

No, its poor code. Previously PHP would not complain if you tried to compact a non-existing variable. Obviously this is not a good idea. Better that you know that you messed up in your code, so later versions throw an error.

PHP7.2 is now no longer supported so you should fix your code and use php7.4 or 8.x

2 likes

Please or to participate in this conversation.