Search code examples
laravellaravel-livewire

How protect public Laravel livewire property from manipulation?


I am mounting my component with an object $form which I need to access between requests. The data in $form is not secret, but should not be tampered with so I would like to make it a protected property. Though only public properties are preserved between requests leaving it exposed to front end.

If possible, how can I prevent manipulation on this public property?

I tried a check

public function updating($key, $value)
{
    if($key === 'form') return;
}

But I don't think that really does anything.

Also, using sessions is not an alternative in my situation.

Any ideas?


Solution

  • In my opinion you have these options:

    1. Do not store the data as public property, instead just pass it to your view in the render() method.

      public function render(){
         return view('Livewire.nameofyourview ', [
            'form' => YourDataSource::get()
         ]);
      } 
      

      This will refetch the data on every interaction with your component. You can access this in your template as before as $form. Make sure to remove $form as public property. Manipulating the $form data form client/user site isn't possible with this solution. Docs

    2. Use validation rules if you need your user/client to manipulate the data, but only ways you expect.

      protected $rules = [
          'form.name' => 'required|min:6',
          'form.email' => 'required|email',
      ];
      

      Full Example

    3. Use Laravel cache to preserve data between requests. This technique is useful if you can't refetch your data from the source, like when it was passed to your Livewire component as parameter (<livewire:form-component :form="$form">).

      /* Cache the data on component mount */
      public function mount($form)
      {
          Cache::set($this->id."_form", $form, 60*10);
      }
      
      public function someFunction()
      {
          /* read the data form cache, if you need it again */
          cache($this->id."_form");
      }