<?php
namespace App\Http\Livewire\Posts;
use Livewire\Component;
use Livewire\WithPagination;
use App\Models\Post;
class Posts extends Component
{
use WithPagination;
public $searchTerm;
public $postsx, $title, $body, $post_id;
public $isOpen = 0;
public function mount()
{
$query = '%'.$this->searchTerm.'%';
// Perfect
//$this->postsx = Post::all();
// With Error
$this->postsx = Post::where(function($sub_query){
$sub_query->where('title', 'like', '%'.$this->searchTerm.'%')
->orWhere('body', 'like', '%'.$this->searchTerm.'%');
})->paginate(10);
}
public function render()
{
return view('livewire.posts.posts', [
'posts' => $this->postsx
]);
}
Error with Pagination
This error is not because of the pagination
you are setting an invalid type on public property.
you can make a method in your model and access it directly in your component.
Post Model
class Post extends ...
{
public function scopeSearch($niddle)
{
return $this->where(function ($subQuery) {
$subQuery->where('title', 'like', '%' . $niddle . '%')
->orWhere('body', 'like', '%' . $niddle . '%');
});
}
}
In your Component
return view('livewire.posts.posts', [
'posts' => Post::search($this->searchTerm)->paginate(10)
]);
no need to $this->postsx
1 Like