I'm trying to CRUD with livewire and I'm having some troubles.
Here you can see my main controller component.
class Topics extends Component
{
public function index()
{
$topics = Topic::all();
return view('topics.index', ['topics'=>$topics]);
}
public function create()
{
return view('topics.create');
} /* The store function is in a single component as I say after */
public function show(Topic $topic)
{
return view('topics.show', compact('topic'));
}
public function edit(Topic $topic)
{
return view('topics.edit', compact('topic'));
}
public function destroy(Topic $topic)
{
//
}
public function render()
{
return view('livewire.topics');
}
}
At the beginning I would try to regroup all the CRUD functions in one file livewire. But it was impossible for me to use the store function. I needed to create a component only for storing. Maybe you have a solution for that too? But it's not my main problem here.
As the store function, the update function doesn't work, so I created a component name "edit".
Here is the problem.
I can :
I can't give to this component the information of the topic I clicked on.
$topic variable is unsigned.
How, in your opinion, can I give to this component the information of the topic I want to edit?
I put here the rest of my actual view and controller.
The store component:
class Store extends Component
{
protected $rules = [
'title' => 'required',
'content' => 'required',
];
public $title;
public $content;
public $user_id;
public function store()
{
$this->user_id = auth()->user()->id;
$this->validate();
$topic = Topic::create([
'title' => $this->title,
'content' => $this->content,
'user_id' => $this->user_id,
]);
return redirect()->route('topics.show', $topic->id);
}
public function render()
{
return view('livewire.test');
}
}
The edit controller's component:
class Edit extends Topics
{
public function render()
{
return view('topics.edit');
}
}
As you can see I tried to extend the Topics controller to pass the $topic... but it doesn't work of course.
I tried:
<div>
<livewire:edit :topic="$topic">
</div>
And some other thing.
Thank you for helping me
You need to define the mount function in your Livewire:
class Store extends Component
{
protected $rules = [ ... ];
public $topic = NULL;
public function mount($topic) {
$this->topic = $topic
}
In Livewire components, you use mount() instead of a class constructor __construct() like you may be used to. NB: mount() is only ever called when the component is first mounted and will not be called again even when the component is refreshed or rerendered.
In addition in your case, if you are separating the View model like that you might as well consider to have the Livewire initiate separately. so in Store also add a $listener and then use javascript to load the Livewire...but that is a whole another question and another answer.