In my Laravel 8 Jetstream installation based on livewire, I have a component that lists some records.
These records can be filtered on the front-end based on some criterias in real time with live update and paginated.
Nothing special yet and everything works as expected.
Now, I need to implement an export()
method that will export the filtered data and I don't know how or not even sure if it's possible to access the data variables from the render()
method so I can use only the filtered data for the export.
Pages
component
public $type;
public $color;
public function export() {
$dataToExport = 'here I need the filtered data from $pages variables from render method so I can export them';
}
public function render() {
$pages = Page::when($this->type, function($query) {
$query->where('type', $this->type);
})
->when($this->color, function($query) {
$query->where('color', $this->color);
})
...
->paginate();
return view('livewire.page.index', [
'pages' => $pages
]);
}
I'm using the render()
method to prepare the data by querying the database because it renders and outputs the correct data when I change something on the front-end.
Basically, everything works fine, but on the front-end I have a button that will trigger the export
method, so the filtered data must be available for the method to be exported.
I also choose this approach because I think it's safer not to expose the data in a public property. Maybe I'm not using the best approach for this, so I'm open to a better solution that takes care of performance and security as well.
BTW: What's the difference (in terms of security and/or performace) of using variables within render()
method, or using properties?
There'll be no significant difference in term of performance or security using the data on the render or on a public property, both approach will expose the data to the javascript. If you're dealing with sensitive data I wouldn't recommend to use Livewire.
From your code, I think you can get the same query using a function:
public $type;
public $color;
public function export() {
$dataToExport = $this->pages()->someWayOfExportTheFilteredData();
}
public function render() {
return view('livewire.page.index', [
'pages' => $this->pages()->paginate()
]);
}
protected function pages()
{
return Page::when($this->type, function($query) {
$query->where('type', $this->type);
})
->when($this->color, function($query) {
$query->where('color', $this->color);
})
...
}