So, it’s my first LiveWire
learning Project.
Just to the point, I’m making a Livewire Component called User using php artisan make:livewire user
and then this is what I got
First User.php
<?php
namespace AppHttpLivewire;
use LivewireComponent;
class User extends Component
{
public function render()
{
return view('livewire.user.index'); //i've updated this
}
}
And so, I want to make a create user at different pages. NOTES: Ive already use turbolinks for the SPA, and when I create like the traditional Laravel Controller like
Web.php
Route::get('/user', User::class)->name('user.index');
Route::get('/user/create',[User::class, 'create'])->name('user.create');
User.php (livewire component)
<?php
namespace AppHttpLivewire;
use LivewireComponent;
class User extends Component
{
public function render()
{
return view('livewire.user.index');
}
// This is what i create
public function create()
{
return view('livewire.user.create')
->extends('layouts.app')
->section('contents');
}
}
It doesn’t give me the parent templates (It doesn’t run into layouts.app and go to contents, it just show blank pages), I’ve tried to extends it with layouts.app and the section
layouts/app.blade.php
<div class="flex h-screen bg-gray-50 dark:bg-gray-900" :class="{ 'overflow-hidden': isSideMenuOpen }">
@include('layouts.include._sidebar')
<div class="flex flex-col flex-1 w-full">
@include('layouts.include._navbar')
<main class="h-full overflow-y-auto">
<div class="container px-6 mx-auto grid">
{{-- {{ $slot }} --}}
@yield('contents')
</div>
</main>
</div>
</div>
My question:
can we do like standart laravel controller with public function create inside user component OR we have to make a new component called UserCreate? Thanks!
Advertisement
Answer
You can handle this by different ways, depend of you. One can be have an UserForm component to handle the create/edit forms, and in User’s create component call to render the UserForm component to create new one.
public function create()
{
return redirect()->route('user.create');
}
in web.php
Route::get('/user/create', [UserForm::class])->name('user.create');
Route::get('/user/edit/{user?}', [UserForm::class])->name('user.edit');
and UserForm component
public $email, $name;
public $user;
public $option = '';
public function mount($user = null)
{
if(is_null($user)) {
// some initialization
$this->option = 'create';
}
else {
$this->user = User::find($user);
$this->option = 'edit';
}
}
public function render()
{
return view('user-form');
}
public funcion store()
{
if($this->option == 'create') {
//create handler
}
else {
//edit handler
}
}
instead use redirect you can use modals and render UserForm inside a modal you have in User component. As I told you, this can be do it by different ways