Reputation: 3450
New to livewire, and trying to convert an existing form to a livewire component.
When I submit the form, I'm getting this error:
Typed property App\Http\Livewire\LocationInfo::$location must not be accessed before initialization
I'm not sure how to make this work, or what I'm doing wrong. I was expecting that the save() method would know about $this->location
, but maybe I'm misunderstanding something. Can't seem to find anything different in the docs from what I'm doing. I've also looked through other questions with the same error and not finding an answer.
I can move the Log statement to the mount method or the render method and it will log the correct info. I don't understand why it's not available to the save() method.
Here's my livewire component:
class LocationInfo extends Component
{
public Object $states;
public Location $location;
protected $rules = [
'location.name' => ['required', 'string', 'max:150'],
...
];
public function mount(Location $location)
{
$this->location = $location;
$this->states = USState::all();
}
public function render()
{
return view('livewire.location-info');
}
public function save()
{
Log::debug($this->location);
}
}
and here's my form:
<div class="modal fade" id="location_info_modal" tabindex="-1" aria-labelledby="location_info_modal" aria-hidden="true">
<div class="modal-dialog modal-lg">
<form wire:submit.prevent="save" class="" id="location_info_form" method="POST" action="/locations/{{ $location->id }}">
<div class="modal-content">
<div class="modal-header d-flex justify-content-between">
<div id="modal_header" class="d-flex justify-content-start align-items-center">
<h5 class="modal-title pe-3">Edit Location Info</h5>
</div>
<button type="button" class="btn-close" data-bs-dismiss="modal"
aria-label="btn-close"></button>
</div>
<div class="modal-body">
<div class="row">
@csrf
<div class="mb-3 col-md-8">
<label for="name" class="form-label">Location Name</label>
<input wire:model="location.name" type="text" class="form-control" id="name" placeholder="name" name="name" value="{{ $location->name ?? '' }}" data-inputmask-regex="[A-Za-z0-9#.,''-() &]+">
@error('location.name') <span class="error">{{ $message }}</span> @enderror
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary save_btn" id="location_info_save" disabled>Save</button>
</div>
</div>
</form>
</div>
</div>
and here's my route:
Route::post('/locations/{id}', [LocationInfo::class, 'save'])
->middleware('auth');
Upvotes: 1
Views: 5108
Reputation: 811
I had this error before to me it was the typed property
try to remove it like:
public $location;
public function mount(Location $location)
{
$this->location = $location;
}
or remove the one in the mount:
public Location $location;
public function mount()
{
$this->location = new Location();
}
Upvotes: 3