hotwired-laravel / turbo-laravel

This package gives you a set of conventions to make the most out of Hotwire in Laravel.
https://turbo-laravel.com
MIT License
803 stars 50 forks source link

New Turbo Stream HTTP Response API #19

Closed tonysm closed 3 years ago

tonysm commented 3 years ago

Added

Changed

Removed


There was not really a way to manually construct a Turbo Stream response before. It relied on conventions or using custom turbo stream views, which had precedence over generating a Turbo Stream response.

The precedence of custom Turbo Stream views is now gone. If you want to use custom turbo stream views, you can manually do that by using the response()->turboStreamView() helper (Breaking Change).

Now, you can manually construct Turbo Stream responses, like so:

return response()->turboStream()
  ->target('comments')
  ->action('append')
  ->view('comments._comment', ['comment' => $comment]);

There are also a couple of shorthand syntaxes, like so:

response()->turboStream()->append($comment);
response()->turboStream()->prepend($comment);
response()->turboStream()->replace($comment);
response()->turboStream()->update($comment);
response()->turboStream()->remove($comment);

These will figure out the correct target, action, and view/partial to use based on the conventions.

They also return the same "pending object" as the manually constructing responses one so you can override the defaults, like so:

response()->turboStream()->append($comment)->target('post_comments');

The old style of passing the model as a param to the turboStream() macro still works. However, it won't pick up the custom turbo stream views anymore.

return response()->turboStream($comment);

This will render a remove Turbo Stream if the model was deleted (or if it's trashed, in case we have a soft-deleted model), or a append if it was a recently created model (you can override the action as the second parameter with this syntax), or a replace Turbo Stream if the model was just updated (you can also override the action as the second parameter with this syntax for updated too), something like:

response()->turboStream($comment, 'prepend'); // if the model was created, it will render a prepend Turbo Stream. Default: append
response()->turboStream($comment, 'update'); // if the model was updated, it will render an update Turbo Stream. Default: replace

Issue: https://github.com/tonysm/turbo-laravel/issues/18

TODO: