You can make manual visits with Inertia's router. So, you can just take the optimistic approach; toggle the checkbox/button, make the Request (using router.post or router.put) and only back out of the toggled state if there is a problem (i.e. non-2xx response); so no redirect, only something successful like response()->noContent() in the Controller action
Inertia.js: Are there situations where an axios request is just better?
I'm a little confused on whether I should handle all my requests "the inertia way". Here I have an example of a MovieController:
class MovieController extends Controller
{
public function show(string $slug)
{
$movie = Movie::where('slug', $slug)->firstOrFail();
// in the Movie page, we have a toggle that adds/removes movie from user's favorites
return Inertia::render('Movie', [
'movie' => [
...$movie->toArray(),
'isFavorited' => MovieFavorite::where([
'user_id' => auth()->id(),
'movie_id' => $movie->id,
])->exists(),
],
]);
}
public function toggleFavorite(string $slug)
{
$movie = Movie::where('slug', $slug)->firstOrFail();
$activeFavorite = MovieFavorite::where([
'user_id' => auth()->id(),
'movie_id' => $movie->id,
]);
if ($activeFavorite->exists()) {
$activeFavorite->delete();
} else {
MovieFavorite::insert([
'user_id' => auth()->id(),
'movie_id' => $movie->id,
]);
}
return back();
}
}
From what I can tell, the return back() in toggleFavorite() causes the logic in show() to be re-executed. This means that the two database queries (which only need to be made on initial page load) are made again for the reload. Then basically the entire page gets re-rendered to accommodate the one small change that is isFavorited.
Is the description above accurate? If it is, isn't this kind of inefficient? I've experimented with partial reloads but can't seem to figure out how exactly to apply them here. It almost feels like a plain axios request is just a better approach for this scenario. Please prove me right or wrong in the replies.
Please or to participate in this conversation.