how to bind the model relation value in livewire wire:model? - laravel

There is a Product model with hasmany descriptions relationship.
descriptions relation has two columns, count, body.
How I must define the wire:model value to show the selected product descriptions values in Livewire Update component?
I must mention getting data from relation works fine just can't show data in the input tag of wire:model attribute! I think the problem is on the key definition of protected $rules or wire:model value!
the Update Class:
public $product;
protected $listeners = ['selectedProduct'];
public function selectedProduct($id){
$this->product = Product::with('descriptions')->findOrFail($id);
}
protected $rules = [
"description.count" => "required",
"description.body" => "required",
];
the livewire view:
#if($product)
#foreach($product->descriptions as $description)
<input type="text" wire:model="description.count">
<texatarea wire:model="description.body"></texatarea>
#endforeach
#endif
the loop and number of filed is repeated correct but no data is shown!

There are a few things I'd like to mention, first is that your view should always only have one root HTML element - and subsequent elements that is generated in a loop should also have one unique root element inside, that has wire:key on it. The wire:key should be something unique on your page.
Then we need to have a look at the rules - its correct that any models needs a rule to be visible in input-elements, but you have a collection of elements, so the rules need to reflect that. To do that, you specify a wildcard as the key
protected $rules = [
"description.*.count" => "required",
"description.*.body" => "required",
];
The fields then has to be bound towards an index, so Livewire knows its in a collection.
<div>
#if ($product)
#foreach($product->descriptions as $index=>$description)
<div wire:key="product-description-{{ $description->id }}">
<input type="text" wire:model="descriptions.{{ $index }}.count">
<texatarea wire:model="descriptions.{{ $index }}.body"></texatarea>
</div>
#endforeach
#endif
</div>
Finally, you need to declare the descriptions as a public property on the class, and store them there.
public $product;
public $descriptions;
protected $listeners = ['selectedProduct'];
protected $rules = [
"description.*.count" => "required",
"description.*.body" => "required",
];
public function selectedProduct($id){
$this->product = Product::with('descriptions')->findOrFail($id);
$this->descriptions = $this->product->descriptions;
}

Related

How to dynamically add input fields with livewire

I want add new Inputbox to be created when the user clicks the add button.
I tried the following code but it didn't work, And I get the following error:
get_class(): Argument #1 ($object) must be of type object, string
given
class Test extends Component
{
public $tests=[''];
public function render()
{
return view('livewire.test');
}
public function mount()
{
$this->tests = Test::all();
}
public function add()
{
$this->tests[] = '';
}
}
<div>
<form wire:submit.prevent="submit">
#foreach($tests as $index=>$test)
<div>
<label for="title">
<input wire:model="title.{{$index}}" type="text">
</label>
</div>
#endforeach
<button type="submit">Save</button>
</form>
<button wire:click="add()">ADD MORE</button>
</div>
There are a few issues to address here, so I will provide some background information and try to be as descriptive as possible.
In your mount function you assign a collection of Test objects to your tests array property:
public function mount()
{
$this->tests = Test::all(); // <-- returns a collection of Test models
}
This overrides the default value and type you have assigned to tests which is an array:
/*
* This declares $tests to be an array
* but this becomes a Collection due to your mount method
*/
public $tests = [''];
Yet in your add function you're adding a string:
public function add()
{
$this->tests[] = '';
}
So you're getting the error because you're trying to add a string to a variable that is a collection of Test models. What you likey want to do is add a new empty Test model.
public function add()
{
$this->tests->push(Test::make());
}
However, the above will not work as you're working with an existing database collection and so you'll get the following error:
Queueing collections with multiple model connections is not supported.
Therefore to achieve your goal of adding a new Test we need to approach this differently.
app\Http\Livewire\Test.php
<?php
namespace App\Http\Livewire;
use Illuminate\Support\Collection;
use Livewire\Component;
class Test extends Component
{
// A collection of your models from the database
public Collection $tests;
// A conditional variable that we use to show/hide the add new model inputs
public bool $isAdding = false;
// A variable to hold our new empty model during creation
public \App\Models\Test $toAdd;
// Validation rules
// These are required in order for Livewire to successfull bind to model properties using wire:model
// Add any other validation requirements for your other model properties that you bind to
protected $rules = [
'tests.*.title' => ['required'],
'toAdd.title' => ['required']
];
// Livewires implementation of a constructor
public function mount()
{
// Set some default values for the component
$this->prepare();
}
public function render()
{
return view('livewire.test');
}
//
public function add()
{
// Set the show/hide variable to true so that the new inputs section is shown
$this->isAdding = true;
}
// Save the new model data
public function save()
{
// Save the model to the database
$this->toAdd->save();
// Clean things up
$this->prepare();
}
// Just a helper method for performing repeated functionality
public function prepare()
{
// Get all the required models from the database and assign our local variable
$this->tests = \App\Models\Test::all();
// Assign an empty model to the toAdd variable
$this->toAdd = \App\Models\Test::make();
// Set the isAdding show/hide property to false, which will hide the new model inputs
$this->isAdding = false;
}
}
resources\views\livewire\test.blade.php
<div>
<!-- loop over all your test models -->
#foreach ($tests as $index => $test)
<!-- the :key attribute is essential in loops so that livewire doesnt run into DOM diffing issues -->
<div :key="tests_{{ $index }}">
<label for="tests_{{ $index }}_title">Title {{ $index }}
<input type="text" id="tests_{{ $index }}_title" name="tests_{{ $index }}_title"
wire:model="tests.{{ $index }}.title" :key="tests_{{ $index }}_title" />
</label>
</div>
#endforeach
<!-- Only show the new model inputs if isAdding is true -->
#if ($isAdding)
<!-- this doesnt need a :key as its not in a loop -->
<div>
<label for="title">Title
<input type="text" id="title" name="title" wire:model="toAdd.title" />
</label>
<!-- triggers the save function on the component -->
<button type="button" wire:click="save">Save</button>
</div>
#endif
<!-- triggers the add function on the component -->
<button type="button" wire:click="add">Add More</button>
</div>
Hopefully, with the comments I have added the above makes sense.
Update
Is it possible to create several input boxes and finally save all the data at once?
That is entirely possible yes. Due to some limitations with Livewire, specifically it not knowing how to hydrate Eloquent Models in a Collection correctly, we need to use a little wizardry to make it work.
app\Http\Livewire\Test.php
<?php
namespace App\Http\Livewire;
use Illuminate\Support\Collection;
use Livewire\Component;
class Test extends Component
{
// A collection of your models from the database
public Collection $tests;
// A conditional variable that we use to show/hide the add new model inputs
public bool $isAdding = false;
// A variable to hold our new empty models during creation
public Collection $toAdd;
// Validation rules
// These are required in order for Livewire to successfull bind to model properties using wire:model
// Add any other validation requirements for your other model properties that you bind to
protected $rules = [
'tests.*.title' => ['required'],
'toAdd.*.title' => ['required']
];
// Livewires implementation of a constructor
public function mount()
{
$this->cleanUp(true);
}
public function hydrate()
{
// Get our stored Test model data from the session
// The reason for this is explained further down
$this->toAdd = session()->get('toAdd', collect());
}
public function render()
{
return view('livewire.test');
}
public function add()
{
$this->isAdding = true;
// Push (add) a new empty Test model to the collection
$this->toAdd->push(\App\Models\Test::make());
// Save the value of the toAdd collection to a session
// This is required because Livewire doesnt understand how to hydrate an empty model
// So simply adding a model results in the previous elements being converted to an array
session()->put('toAdd', $this->toAdd);
}
public function save($key)
{
// Save the model to the database
$this->toAdd->first(function ($item, $k) use ($key) {
return $key == $k;
})->save();
// Remove it from the toAdd collection so that it is removed from the Add More list
$this->toAdd->forget($key);
// Clean things up
$this->cleanUp(!$this->toAdd->count());
}
public function saveAll()
{
$this->toAdd->each(function ($item) {
$item->save();
});
$this->cleanUp(true);
}
// Just a helper method for performing repeated functionality
public function cleanUp(bool $reset = false)
{
// Get all the required models from the database and assign our local variable
$this->tests = \App\Models\Test::all();
// If there are no items in the toAdd collection, do some cleanup
// This will reset things on page refresh, although you might not want that to happen
// If not, consider what you want to happen and change accordingly
if ($reset) {
$this->toAdd = collect();
$this->isAdding = false;
session()->forget('toAdd');
}
}
}
resources\views\livewire\test.blade.php
<div>
<!-- loop over all your test models -->
#foreach ($tests as $index => $test)
<!-- the :key attribute is essential in loops so that livewire doesnt run into DOM diffing issues -->
<div :key="tests_{{ $index }}">
<label for="tests_{{ $index }}_title">Title {{ $index }}
<input type="text" id="tests_{{ $index }}_title" name="tests_{{ $index }}_title"
wire:model="tests.{{ $index }}.title" :key="tests_{{ $index }}_title" />
</label>
</div>
#endforeach
<!-- Only show the new model inputs if isAdding is true -->
#if ($isAdding)
<div>
#foreach ($toAdd as $index => $value)
<div :key="toAdd_{{ $index }}">
<label for="toAdd_{{ $index }}_title">New Title {{ $index }}
<input type="text" id="toAdd_{{ $index }}_title"
name="toAdd_{{ $index }}_title" wire:model="toAdd.{{ $index }}.title"
:key="toAdd_{{ $index }}_title" />
</label>
<!-- triggers the save function on the component -->
<button type="button" wire:click="save({{ $index }})" :key="toAdd_{{ $index }}_save">Save</button>
</div>
#endforeach
<button type="button" wire:click="saveAll">Save All</button>
</div>
#endif
<!-- triggers the add function on the component -->
<button type="button" wire:click="add">Add More</button>
</div>
I've not removed some of the previous comments and not commented on the code that should be pretty obvious what it is doing.
I did rename the prepare function to cleanUp and it seemed more appropriate.
I also provided functions for saving an individual Test model, or all at the same time. You might want to be able to do one or the other or both at some point so seemed useful.

Livewire Nested Components Sub-Form

I'm having trouble understanding Nested Components. I'm mainly using my nested components to provide a Modal (nested component) in my main components. Ex: a Modal form for some additional info in my Forms on main components.
I hope what I'm trying to accomplish is possible. I have a "partial form" for Checks input in many components. Each component has the same exact validation rules and required Model quieres. I want to remove all of those, put them in 1 nested component and then call something like #livewire('checks.checks-form') in each main component.
Something like this:
Main Component TimesheetForm
View livewire.timesheets.payment-form :
some TimesheetForm inputs here
#livewire('checks.checks-form')
some TimesheetForm inputs here
Although the data from my nested component (ChecksForm) is loaded onto the main component views, the main component views still try to load the validation rules from itself instead of the nested component. I was really hoping to avoid repeting both, my nested component date (which seems to work) AND my nested component validation rules.
Is this something that can be achieved? (I'm sure since anything I have ever struggled with in the TALL stack always comes back with positive results). Thank you for any pointers in the right direction! - Patryk
App\Http\Livewire\TimesheetPaymentForm:
class TimesheetPaymentForm extends Component
{
public User $user;
protected function rules()
{
return [
'user.full_name' => 'nullable',
'weekly_timesheets.*.checkbox' => 'nullable',
'employee_weekly_timesheets.*.checkbox' => 'nullable',
'user_paid_expenses.*.checkbox' => 'nullable',
];
}
...
public function render()
{
return view('livewire.timesheets.payment-form');
}
payment-form.blade.php:
{{-- FORM --}}
{{-- ROWS --}}
<x-forms.row
wire: model"user.full_name"
errorName="user.full_name"
name="user.full_name"
text="Payee"
type="text"
disabled
>
</x-forms.row>
#livewire('checks.checks-form')
App\Http\Livewire\Checks: Want to use this inside my TimesheetPaymentForm
{
public $check = NULL;
public $check_input = NULL;
protected function rules()
{
return [
'check.date' => 'required',
'check.paid_by' => 'required_without:check.bank_account_id',
'check.bank_account_id' => 'required_without:check.paid_by',
'check.check_type' => 'required_with:check.bank_account_id',
'check.check_number' => 'required_if:check.check_type,Check',
'check.invoice' => 'required_with:check.paid_by',
];
}
...
public function render()
{
$bank_accounts = BankAccount::where('type', 'Checking')->get();
$employees = auth()->user()->vendor->users()->where('is_employed', 1)->whereNot('users.id', auth()->user()->id)->get();
return view('livewire.checks._payment_form', [
'bank_accounts' => $bank_accounts,
'employees' => $employees,
]);
}
_payment.form.blade.php:
...
<x-forms.row
wire:model="check.paid_by"
errorName="check.paid_by"
name="paid_by"
text="Paid By"
type="dropdown"
>
<option value="" readonly>{{auth()->user()->vendor->business_name}}</option>
#foreach ($employees as $employee)
<option value="{{$employee->id}}">{{$employee->first_name}}</option>
#endforeach
</x-forms.row>
<div
x-data="{ open: #entangle('check.paid_by') }"
x-show="!open"
x-transition.duration.150ms
>
#include('livewire.checks._include_form')
</div>
<div
x-data="{ open: #entangle('check.paid_by') }"
x-show="open"
x-transition.duration.150ms
>
<x-forms.row
wire:model="check.invoice"
name="check.invoice"
errorName="check.invoice"
text="Reference"
type="text"
>
</x-forms. Row>
</div>
...

Updating form in Laravel goes wrong

This may be a very simple question, but I can't figure it out! and that's frustrating.
I do my best to explain everything step by step.
This a small Todo list project in Laravel 8
A user can create a Project.
When user clicks on a created project, he goes to the project page (show page)
ShowController.php
public function show(Project $project)
{
return view('projects.show', compact('project'));
}
In the show page the user can add comments via a textarea form field.
show.blade.php
<form action="{{ route('project.update',['project' => $project]) }}" method="post">
#csrf
#method('PUT')
<textarea name="notes" placeholder="Add notes">{{ $project->notes ?? '' }}</textarea>
<button type="submit">Save</button>
</form>
Where it goes wrong is here, by updating the project! as soon as the user enters something in the comments field and clicks save, the form indicates that the following items are required:
The owner_id, title, description field are required. While the model is sent to the show blade page and then in the form action route.
What am I doing wrong here?
UpdateController.php
public function update(ProjectRequest $request, Project $project)
{
$validated = $request->validated();
$project->update($validated);
return redirect($project->path());
}
ProjectRequest.php
public function rules(): array
{
return [
'owner_id' => 'required',
'title' => 'required',
'description' => 'required',
'notes' => 'nullable',
];
web.php
use App\Http\Controllers\Projects\CreateController;
use App\Http\Controllers\Projects\IndexController;
use App\Http\Controllers\Projects\ShowController;
use App\Http\Controllers\Projects\StoreController;
use App\Http\Controllers\Projects\UpdateController;
use Illuminate\Support\Facades\Route;
Route::get('/', [IndexController::class, 'index'])->name('project.index');
Route::get('/projects/create', [CreateController::class, 'create'])->name('project.create');
Route::post('/projects', [StoreController::class, 'store'])->name('project.store');
Route::get('/projects/{project}', [ShowController::class, 'show'])->name('project.show');
Route::put('/projects/{project}', [UpdateController::class, 'update'])->name('project.update');
migration
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('owner_id');
$table->string('title');
$table->text('description');
$table->text('notes')->nullable();
$table->timestamps();
$table->foreign('owner_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}
You have required rules for fields that does not exist in form. So validation correctly fails.
If you use these rules for storing data, and want different one for updating, then you have at least three solutions:
Make separate form request file. So instead ProjectRequest do for
ex. ProjectUpdateRequest and ProjectStoreRequest.
Use single Request, but detect if it is Update or Store inside rules() function, and return different rules array based on it. Related question: Laravel form request validation on store and update use same validation
Don't use custom FormRequest at all for Update, just make this single validation inside controller update() function.
https://laravel.com/docs/8.x/validation#quick-writing-the-validation-logic
Option 2 seems to be best solution, because you will not have to repeat validation rules for "notes" input in multiple places - everything will be in single file.
If the fields are not required then take them out of your $required array and it should work.
When injecting a model ID to a route or controller action, you will
often query the database to retrieve the model that corresponds to
that ID. Laravel route model binding provides a convenient way to
automatically inject the model instances directly into your routes.
For example, instead of injecting a user's ID, you can inject the
entire User model instance that matches the given ID.
Reference
show.blade.php
<form action="{{ route('project.update',['project' => $project->id]) }}" method="post">
#csrf
#method('PUT')
<textarea name="notes" placeholder="Add notes">{{ $project->notes ?? '' }}</textarea>
<button type="submit">Save</button>
</form>
Also, to update a column, you do not need to validate and update all the columns.
UpdateController.php
public function update(Request $request, Project $project)
{
$request->validate([
'title' => 'nullable|string',
]);
$project->update(['notes' => $request->notes ?? '']);
return redirect($project->path());
}
Note: Add use Illuminate\Http\Request; to the first UpdateController.php file.

how to validate atleast one value of form input array in laravel request?

I am passing array input to store function .
<div class="col-md-4 form-group-sub mt-2 date_">
<input type="text" name="date[]" class="form-control datepicker" placeholder="Date">
</div>
this array should be have atleast one field filled . If all the values are null i don't to submit this form how shoult i validate in request
public function rules()
{
return [
'date.*' => '?'
];
}
I suppose you can try to make sure date is an array with a minimum size and then try to validate the elements of it:
'date' => 'array|min:1',
'date.*' => 'filled',
Laravel 7.x Docs - Validation - Available Rules array
Laravel 7.x Docs - Validation - Available Rules min
Laravel 7.x Docs - Validation - Available Rules filled
this array should be have atleast one field filled . If all the values
are null i don't to submit this form
This will pass
['some date', NULL, NULL, NULL]
This will fail
[NULL, NULL]
This will fail
[]
Anything other than array will fail.
Use a combination of
array, min:1 and a custom rule that checks the null condition.
https://laravel.com/docs/7.x/validation#rule-array
https://laravel.com/docs/7.x/validation#rule-min
https://laravel.com/docs/7.x/validation#custom-validation-rules
public function rules()
{
return [
'date' => ['array', 'min:1', new DateCheck]
];
}
DateCheck rule will check, that there should be at least one element in the array, that is not null.
Inside DateCheck Rule
public function passes($attribute, $value)
{
$dates = $value;
foreach($dates as $date){
if(isset($date)){
return TRUE;
}
}
return FALSE;
}
public function message()
{
return 'There should be at least one date that is not NULL.';
}

mass assignment on [App\comment] in laravel

trying to add a comment in my blog , so i got this new error :
Add [body] to fillable property to allow mass assignment on [App\comment].
this is thr controller :
public function store (blog $getid)
{
comment::create([
'body' =>request('body'),
'blog_id'=> $getid->id
]);
return view('blog');
}
and this is the form :
<form method="POST" action="/blog/{{$showme->id}}/store" >
#csrf
<label> Commentaire </label> </br>
<textarea name="body" id="" cols="30" rows="2"></textarea> </br>
<button type="submit"> Ajouter commentaire</button>
</form>
web.php :
Route::post('blog/{getid}/store', 'commentcontroller#store');
To avoid filling in any given property, Laravel has mass asignment protection. The properties you want to be filled should be in the $fillable property on the model.
class Comment {
$fillable = ['body', 'blog_id'];
}
Bonus
For keeping up with standards. You should not name your classes in lower case, it should be Blog and Comment, both in PHP code and in file name.
Id should not be filled but associated, so they will be loaded properly on the model. So imagine your Comment model having the blog relationship.
class Comment {
public function blog() {
return $this->belongsTo(Blog::class);
}
}
You should assign it instead. Where you would get the Blog by using Model binding, therefor you should name the parameter $blog so the binding will work. Additionally using Request dependency injected, is also a good approach.
use Illuminate\Http\Request;
public function store(Request $request, Blog $blog) {
$comment = new Comment(['body' => $request->input('body')]);
$comment->blog()->associate($blog);
$comment->save();
}

Resources