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

woweya's avatar
Level 1

Using $this when not in object context (Script JS)

Hello to everyone, when in my PHP Blade View I use:

@script
<script>


</script>
@endscript

It returns an Exception which is: "Using $this when not in object context" Why is that? My controller doesn't have even anything inside other than the render method and the mount method.

0 likes
14 replies
salfel's avatar

when using the @script blade directive, you don't need to use the script tag anymore just use

@script 
	//
@endscript
martinbean's avatar

@woweya Well what is that @script directive? Because it’s not one that comes built into Blade as far as know, which suggests is something custom you’ve tried creating.

woweya's avatar
Level 1

@martinbean Im trying to use a Livewire script in a not "Livewire" view, but It still should work?

woweya's avatar
Level 1

@MohamedTammam I know, the problem was not anything you said, but the problem was the fact that it was not inside a livewire view.

1 like
PttRulez's avatar

@woweya i had the same problem today. So what is the general rule here? I can't figure it out. I mean @script helper definitely can be inside non-livewire blade component

bvfi-dev's avatar

When you add @script (Docs ), you no longer need to use $this(Available ONLY inside a Livewire View) in your JS, you should use $wire to access the Livewire Component. You havent stated what your purpose is or what you are trying to do, so can't really help you. Would be a lot better if you actually stated what you wanted to do with this and posted at least some code. Next time please add more details to the question, rather than not even saying what $this is used for, or what you are trying to do. You use @script tags IN LIVEWIRE BLADE VIEWS ONLY, otherwise it doesnt work, simple as that. If you need to add regular JS, just @push it to your main layout scripts.

-------------------------

If you are using @script in a Livewire Blade Component View, then:

If you have a Livewire variable public $postId this can be accessed in the JS like: $wire.postId. If you have a public function submitPost() then you can call $wire.submitPost in the @script. Here's some other stuff you can do with $wire THIS IS THE PURPOSE OF @script, I recommend reading the documentation about JS and AlpineJS more for workarounds in whatever it is you are trying to do.

kevintherm's avatar

Hey, I experienced the same thing, and i fixed it by moving the @script to a livewire component, turns out you can't use @script inside a regular view() instance it must be a livewire or volt component.

Please or to participate in this conversation.