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

Jdubstep1357's avatar

Using variables stored as integers inside of Eloquent Query

I have been looking through Larvel's documentation, and wondering if it is possible to use a stored variable with the value of an integer inside of a query.

For instance:

public $x = 3;

Query1::latest()->take($x)->get();

This displays an error as $x being undefined, even tho I declared it publicly above.

0 likes
3 replies
kokoshneta's avatar

Your code is not valid PHP, so it’s hard to know what the error is. The public keyword is reserved for class properties, but your query example would not be valid in a class (it would have to be in a method definition).

If you’re using the variable in a class, you need to use $this->x instead of $x. Otherwise, you’ll have to show the actual context of your code.

Jdubstep1357's avatar

I made a simple counter upon clicking a button. Every time the button is clicked, it goes up by one.

Here is my Controller in Livewire:

class CartCounter extends Component
{

    public $count = 0;

    public function up() {
        $this->count++;
    }

    public function render()
    {
        return view('livewire.cart-counter',
		// I want $count to be displayed here
      'Display1' => Model1::last()->take($count)->get()
);
    }
}

Here is my blade file:

<div>
    <button wire:click="up">Add To cart</button>
    {{ $count }}

    @foreach($Display1 as $post)
        <tr>
            <td>{{ $post->Query1 }}</td>
        </tr>
    @endforeach
    
</div>

Basically, when the button is clicked, the next last query from the table will be displayed. My question is how to query the stored value ($x) as an integer in the query itself.

kokoshneta's avatar
Level 27

@Jdubstep1357 You’re still showing code that’s not valid PHP.

return view('livewire.cart-counter', 'Display1' => Model1::last()->take($count)->get()

This is syntactically invalid and won’t run. You’re apparently trying to declare an array without using array syntax.

And as I said above, you cannot use class properties by their name alone. I think you need to read the basic PHP documentation on classes to understand how they work.

Your component should look like this:

class CartCounter extends Component {
	public $count = 0;

	public function up() {
		$this->count++;
	}

	public function render() {
		return view(
			'livewire.cart-counter',
			['Display1' => Model1::last()->take($this->count)->get()]
		);
	}
}
1 like

Please or to participate in this conversation.