To address the issue where the redirect is not working as expected in your Livewire component, you need to ensure that the redirect is properly handled within the Livewire lifecycle. The redirect method should be called using Livewire's built-in redirect functionality.
Here's the updated save method with the necessary changes:
public function save(): void
{
$this->validate();
if (is_null($this->pub)) {
$this->pub = Pub::create(
array_merge($this->only('name', 'type_id', 'vat', 'gender'), [
'team_id' => Auth::user()->team_id,
'cb' => Auth::id(),
'ub' => Auth::id(),
'ua' => now()
])
);
$msg_str = 'created';
} else {
if($this->pub->team_id !== Auth::user()->team_id){ // Some thong fishy is going on, halt script
abort(404);
}
// Redirect if another user in the team has updated the post
$pub_old = Pub::findOrFail($this->pub->id);
if(date('Y-m-d H:i:s', strtotime($pub_old->updated_at)) !== (date('Y-m-d H:i:s', strtotime($this->lastUpdatedAt)))){
$this->flash('warning', 'Post could not be updated because someone else has been updated it simultaneously, please try again');
return redirect()->to('/pubs'); // Use Livewire's redirect functionality
}
$this->pub->update(
array_merge($this->only('name', 'type_id', 'vat', 'gender'), [
'team_id' => Auth::user()->team_id,
'ub' => Auth::id()
]) // Add team_id on update just to be sure no one has been posting a malicious team_id
);
$msg_str = 'updated';
}
$this->pub->tags()->sync($this->tags);
$this->flash('success', 'Post successfully ' . $msg_str);
return redirect()->to('/pubs'); // Use Livewire's redirect functionality
}
Explanation:
-
Validation: The
validatemethod is called to ensure the data is correct. -
Create or Update: Depending on whether
$this->pubis null, it either creates a new record or updates an existing one. -
Team Check: It checks if the
team_idmatches the authenticated user's team. -
Concurrency Check: It compares the
updated_attimestamps to detect if another user has updated the post. -
Flash Message and Redirect: If another user has updated the post, it sets a flash message and uses
redirect()->to('/pubs')to redirect the user. This ensures that the redirect is handled correctly within the Livewire lifecycle.
By using redirect()->to('/pubs'), you ensure that the redirect is properly handled by Livewire, which should resolve the issue you're experiencing.