Introducing: Livewire

Introducing a framework that allows for server-side rendering with the productivity of front-end frameworks.

Transcript

00:00:00 hi I'm Caleb or zo I tweet at Caleb or zo slam kill boards are tweeting by kill or zo @ kill or zo I also write blog posts to Caleb or zo calm you can find them there and I do run a podcast with my buddy D Cole that's his new name he loves to be called deep cold by everybody called no plants emerge we talk about layer belt stuff and it's a really good time so last year who here saw my talk last year okay sweetie so it's called embrace the back end and that's right we talked about how like maybe we went a

00:00:40 little bit too far into the whole view world and like there's so much productivity that we sacrificed along the way and how we can kind of rescue some of that productivity by bringing a little bit into the back end but fast forward one year and I can tell you that I think I was wrong and spas are definitely the objective true one stack and JavaScript is objectively better than PHP so this year my talk is titled embraced the front around your house when you're waiting for your dust test to fail I'm just kidding we're gonna

00:01:19 launch live we're who here has heard a livewire awesome sweet all right so we got a couple things to do before we hit the play button or the launch button we're gonna get some background on livewire learn a little bit about it why we want to use it and we'll do a little bit of a demo okay story time so I left my job I left my day job six months ago laughs everybody at Titan left and a job six months ago and decided to go on a sabbatical I'd saved up my pennies and I thought I will climb the mountain top

00:01:51 and I will receive divine insight into the nature of reality but there's no mountains around my house so we went to Disney World the next best thing as we actually moved to Orlando for two months to escape the treacherous Buffalo winter it is a certifiable natural disaster but turns out Florida has their own natural disasters in the form of face eating sors that live in rivers that you bike by but anyway the sabbatical so two days into my sabbatical I came across this tweet because instead of meditating

00:02:22 everyday I was scrolling Twitter Chris McCord he's the creator of a framer called Phoenix which is like an MPC framework for a lick sir like laravel or rails and he put out this project called Phoenix live view and it was pretty bonkers caught my eye and this is a little like right up he did and so he has his UI component it's in the front end and it's a thermostat so he's updating it and he claims that you can write something like this with elixir with back-end code without JavaScript so the Phoenix live view uses

00:02:51 JavaScript but you don't have to use JavaScript to write this and so immediately you know embrace the backend guy my ears are perked and so this is part of the write up he shows kind of the code for it and over there there's like a template it's kind of like a blade template but but there's this weird like click Handler and that can somehow can access a method that lives in the back end which is ridiculous so I don't speak a lick sir so we'll translate it to blade here is here's the basically the equivalent and blade we're

00:03:20 echoing out a value into a template and then let's just pretend that Taylor gave us this magical attribute called laravel click that when somebody clicks that a tag it fires off an ink method that live somewhere in the backend and modifies some state and somehow re renders the template and changes it in the front end so this completely melted my brain as soon as I saw this and I was completely hooked on this idea so I made a proof-of-concept overnight in laravel and the rest is history six months later

00:03:50 we're gonna hit the launch button so this is my little demo that night you can see that look at that hair that's 2 a.m. here and so I'm doing this little click thing and this is all WebSockets and all like backend language and it totally was yeah I loved it so how does this work how do you accomplish something like this so this isn't exactly how Phoenix live view is written or live wire but this gets the point across the fundamental concept underneath this these frameworks so back to our blade view we have that value tag

00:04:19 and let's just say that we get that button that laravel click button we get it in JavaScript so we have button dot add event listener click so we're saying when click the button I want you to send a request off to an endpoint called run method and then you tell them which method you want to run say I want you to run the increment method and I want you to seed it with the initial value of 1 so then the backend does its thing it runs that method a tree renders the template and we get HTML in the response

00:04:44 instead of JSON we're getting HTML and then instead of rendering the template in view we're just shoving that HTML into the Dom with something like container dot outer HTML so this is kind of how it all works so why is this better why would you want to write a thermostat and make server requests every time you click a plus button you probably wouldn't and Java scripts definitely a better way to accomplish that but there's so many other things that this is really good for but so in short this is better because blade is

00:05:13 objectively better than view in all ways just like a couple people clapping a lot of people cringing I joke but there are some distinct advantages simple workflow there's no npm run anything there's no web pack there's none of that stuff it's good old save a file refresh the browser and you have everything you need access to laravel this is like not trivial at all inside of your templates you can access config secret stuff you can access off gates you can access every helper you can access string helpers

00:05:44 like string kabab anyone ok that's my greatest contribution to the laravel framework so you can access laravel all that stuff and that is not to be trifled with that is some serious power and fast and stable tests that's my favorite one you can write a test where you know laravel testing like PHP unit you have refresh databases magic and a sequel Lite in-memory thing and you boot up some model with a factory you hit an endpoint and it runs all the way through the template and actually renders Dom

00:06:12 all instantly alongside all your other tests it's insane there's no Jess there's no dust there's no cypress there's no you know sitting in that tangled web of stuff it's just PHP unit and then whoop which is awesome and this is not news to the rails community like any good concept there are five years ahead of us turbolinks is founded on this basic concept that like we can just Ajax HTML stimulus advocates for a lot of these things pjax and phoenix live view live wire and intercooler so these are all packages

00:06:41 that are basically built on the foundation of hey instead of passing JSON of the front end and letting the front end do the templating which is the hotness at the moment why don't we just keep the templating in the back end and then just sub it out DHH is quoted as saying it allows us to party with productivity like the days of yore I love this quote and there's a million like them of course but it does seem old-school is this just DHH being old mand ehh just you know digging his heels into progress I think not but look no

00:07:08 further than github for Q so this is github and if you open up the inspector chrome dev tools and open up the Ajax requests everything you do in github opens or sends a request and instead of returning JSON its HTML like every single time and it just swaps it into the page this like blew my mind you should do this like anything you do in github will follow this pattern so here I'm like searching the transfer an issue and instead of getting JSON it's getting this HTML and literally shoving it in

00:07:37 there the loading spinner is also not JavaScript so yeah so so like github is a is it enterprise I think it's pretty enterprise so with that that is the why I introduce you to live wire all right let's see some code so this is a basic vanilla laravel application we have the route route that returns a view be welcome view so let's take a look at welcome and welcome is just a pile of HTML okay so first step we're gonna install what's that am I allowed to talk to the audience Oh tailwind nice cool so yeah

00:08:23 definitely tailing we're gonna install live Boyer I'm gonna show you how to install live where you type composer require help or zero slash live wire and then you hit enter and then you wait because composers a little bit slow and then it works but I already did that because live wire is not actually public yet so step two is that live wire assets and that's it live wire is installed and ready to go that is all you need to do to get up and running okay so live wire works like this we're hybrid thing between blade components

00:08:56 and view components but you use them sorry like blade includes you use them like blade include so anywhere you would use an include you could just include a library component so let's say livewire playground okay and then library gives you this artisan make livewire playground and thank you for using livewire and we've generated two files here and we'll take a look at these oh boy monster files here we go all right on the left side we have the class part of a livewire component you can think of this like the

00:09:36 script tag of your single file view component and then on the right side this would be a blade file just like the template tag in a view component and a live where class component class all it needs to have is one render method that's it and the render method returns view or sorry returns blade so anything you do in a controller where your returning blade you can do it right here you could pass data into this blade it's completely a hundred percent vanilla blade okay let's swap this out with some

00:10:03 boilerplate okay so check this out already that loaded right away there's no little view Jas blip like it just loads so it's totally SEO friendly for the first render you don't even need the Java Script it's just you know basically like a fancy blade include let's make it dynamic so instead of this static one we'll pass in something hopefully dynamic will pass in count okay and then to get count into the blade view these library components were kind of like mailable x' where public properties will

00:10:35 just get passed to the view automatically you could pass it through here like any other piece of data but live where wouldn't track it and be all magical and you'll see what I mean in a minute so we render and we have to very good ok let's add some behavior so in view jsut would do something like at click decrement right so live Boyer takes pretty heavily from view syntax so it should feel really familiar if you're a view developer so we can say wire click decrement and then here we'll say wire

00:11:06 click increment okay and now we just need to implement those methods they just exist here there's no little methods key or anything they just exist as methods on the component class so let's do that all right so we have a decrement method and this is straight-up PHP we're just modifying the data property inside this class right ok here we go here's the big reveal moment look at that crazy so pop open Deb tools and we have the github effect every time you do that we're sending a request and in the request we're sending

00:11:45 a little bit of data we're saying hey seed it with this count let's call this method and then the response gives us some other fancy stuff and then a big hunk of HTML and then this uses the same core as Phoenix live view uses a package called morph Dom to do some fancy Dom dipping so it doesn't just wipe everything it intelligently finds the difference and then just subs it out cool so that's pretty awesome let's do one more little test here so there's also data binding which is super valuable in view this V model type thing

00:12:14 and view an angular so if we V modelled foo in view anything that's typed into the input foo that piece of data would now have so livewire has effectively the same thing so we can say why your model and then let's say that we echo it out right here so echo foo and then we'll add this piece of data right here foo and then hello Lera too much okay refresh fingers crossed we type hey and it updates nice yeah so it took a second it actually took an extra 250 milliseconds because as I typed its debounce so I'm not gonna send

00:13:01 an ajax request for every single keystroke other input events you can wire model any input event or any input element like a select element or anything like that but so if i type really fast it's not gonna send a request then i let go and it does nice ok so here is my favorite part of the demo super simple but check this out string length a horribly named PHP method imagine that and super inconsistent with everything else but I also notice I didn't have to refresh because you barely have to refresh with

00:13:33 live wire because you're making these these Brown trips so check it out there you go we have the power of PHP inside of our templates which to me is crazy you can do so many things and if we wanted to like conditionally render something you would think that you would be able to do something like like wire if but you don't need to because you're in blades so you can just do a tiff and we'll say if the string length is greater than 15 then show this little yo alright so then we showed that and it

00:14:04 worked so real quick here's just a fancy thing I want to show off so in view like Adam showed like there's this transition thing in view these transition components and they're pretty good they're alright but like he said like it's such a paint like who here uses these things who here who uses view uses these like transition components okay it's not a ton like I've always been scared of them and they're obnoxious and you have to like keep track of all these classes and figure out like which ones

00:14:29 added at which point in the milliseconds it's kind of crazy but in actuality when are we not like fading and sliding like that's really what we're trying to do most of the time at least I am so livewire has wire transition dot fade okay and now and I'm not gonna refresh and it should work there we go so then we get a nice fade sweet thank you you want to make it longer we do one second and now it takes one second and you can slide and slides in and you can change the direction slide up down whatever so there's that

00:15:08 let's say you want a little bit more power you can actually drop down to something like this and then it'll actually use exactly views system for adding transition classes like fade enter fading to interactive stuff like that cool all right so moving along I think we showed off the syntax enough let's make something a little bit more real okay so instead of making a Twitter clone like I did last time I wanted to do something a little bit different but kind of the same functionality so I mean a clone of a new

00:15:38 social media platform out of Scranton Pennsylvania it's called whoof calm and it's huge right now and it's basically like Twitter except it's whenever and wherever and the CEO Ryan Howard he's a real up-and-comer he doesn't just live he lives yes and so clearly he's got some people in here already some co-workers prison Mike gotta have prison Mike alright so we're gonna hit bark something and we're gonna make a little UI component to create a bark which is essentially like a tweet all right so this page doesn't exist

00:16:12 let's just create it so normally you do route get bark and then you'd pass in you know some blade view and then you'd render it but this is kind of like the view problem like beep sorry view j/s like when you have a whole blade file just for one view component and then Jonathan writings like well I'll just create an ER shaaa so live lawyer does kind of a similar thing route live lawyer bark and we'll create a component called new bark that doesn't exist and we'll see what happens unable to find component that's another

00:16:45 nice thing I just I love like good solid PHP errors a good old stacktrace that I can understand loved it so noubar let's create that artisan make live wire new bark all right and then we have those two files open them up cool so here's the new bark class and then here's the template let's swap this out with a little bit of boilerplate bada bing and there we go so that header or sidebar thing is going to annoy me so we're gonna hide that there we go all right so let's make this do something for starters let's make

00:17:23 woof disabled by default so you can't even touch it but then you start to type in and then this little woof button becomes enabled like some implicit validation so first thing we need to do is we'll want to get whatever is typed into here into a piece of data like with wire model like you saw before so we're model title okay and then we'll add it as a public property public title equals empty string great refresh and now when we type it should be updating but we have no idea of knowing so let's conditionally render a disabled

00:17:53 property right here and so in blade when you're conditionally rendering something you just use blade so let's just use blade okay so here we have we're saying if the title property is empty then show disabled if not don't show anything refresh what you're prodding you need to do and type and there we go so it's disabled by default and then it's not cool so let's add some validation let's say a bark can't be longer than 15 characters so we'll fire a little method on click of this woof we'll call it submit by the way so you

00:18:29 can pass any event here you could be like key down and it uses few syntax like pretty heavily so you could type key down enter or anything like that and it'll just work you can also listen for custom events like it's just kind of a like it falls through to this wildcard listener cool so click Submit and then we'll create this right here if autocomplete works okay validation we'll put there and then we'll create the bark and this is kind of like a store method in a controller and then we'll redirect cool so let's start with

00:19:01 the validation so if you were doing this in a store method in a controller you would do something like this yeah request validate passing some data or you know specify the piece of data and then the validation so this isn't gonna work this is kind of a point of confusion a little bit if you think about it you're not in a normal request cycle like the request is kind of live wires request so this request stuff doesn't actually work but live wire makes it really nice for you and you can just do this validate and this arrow

00:19:26 validate works exactly like the request validator except it references the data inside of your component and it completely acts like it so you could add in custom messaging here it throws that the actual validation exception so none of this will get executed and it also makes the normal blade errors bag available to the view so you can do anything that you would normally do with validation errors all of your snippets they all work so let's just use layer bells fancy new error directive error title message alright so

00:19:56 if there's a title error then show that message and let's see what happens so we type a bunch of characters hopefully over 15 and your bark is too long okay and then it disappears nice so that's great but what have we done that we couldn't just do with the normal form right let's add some real time validation to that input element so real time validation is one of the strong points of live where it's super easy with something like this so there's lifecycle hooks and live wire components there's mount you can actually pass

00:20:22 stuff in the live wire components but we only have 30 minutes so you can mount you can also update it and this will run every time the component is updated every time there's a round-trip but let's say you have a bunch of different data and you want to like keep it to just one piece of data so you can scope it by just kind of magically referencing the piece of data so we'll say when title is updated then let's just run all that validation right here whoopsie okay and and now as we type when we get to 15

00:20:51 characters we're gonna get that real-time validation huit all right so let's create the bark and right now this is just like eloquent create the bark here's the title grab it out of the property and then redirect so this is another one that you'd think that you could do something like this right but that's not how live where it works because it's not a normal request in response so I have a this arrow redirect helper that you can redirect to any route okay so let's see this happen hey there you and there you go okay so

00:21:29 we added it it showed up there pretty cool we got the real-time validation which was nice but still there's a full page load between the two but so library components their components their atomic so we can put them anywhere so let's swap out this bark something with the actual live wire component alright so here's the little template for it we have this bark something we're gonna swap this out with the component to easy live wire new bark okay refresh and there we go it's right there but still so that's cool but you know it's

00:21:59 still a full page reload so I'm not impressed yet let's do something a little bit fancier so you can nest live wire components and they can talk to each other with this like global event system so let's rip all this out and put it into its own live wire component okay live wire call the show barks and then artisan make live where show barks ok so show Burke's show barks and then we'll replace all this stuff with what we just ripped out and there we go but so live wire doesn't inherit the scope kind of

00:22:34 like a blade component it doesn't inherit the scope of the surrounding blade so now this little bark is gonna throw an error and there it is so again to me this is like a feature in itself that you just get undefined barks it's great like right in there it's it's laravel great so for each bark so we need to get barks into here and we pass us in just like we would inside a controller so let's pull the exact code from the route right here yeah and stick it in right there now refresh and we are back in action but still we've just got

00:23:06 back to where we were if I do something it's still gonna be a full page reload okay so here we go let's open new bark so this is the new bark component on the right that's this one here and then this is show barks that kind of wraps it wraps around it so instead of redirecting we can omit an event so we'll omit new bark and you can pass like parameters into these events and stuff like that and then after we admit that let's clear out the title because we're not doing a full page reload so you kind of see like view view patterns

00:23:33 emerge because it's a very similar paradigm so this is totally something I would do in view j/s cool so admit that that event and now in the wrapping component we can listen for the event with a little listeners property and you can listen for events and it's just a map so it's a map between events and then the method to run on the component in this case I don't want to run a method I just want to refresh it so I have this little magic refresh token cool alright so with any luck hey-oh validation and there we go

00:24:03 check it out nice and inside there that little nice animation it's a wire transition but it's like done the old fashioned way there's somewhere there's slide down dot interactive blah blah cool so that's pretty awesome let's kick it up one level further so let's say that you wanted to have like in actual Twitter when you type there's the little letter counter or something like that let's say you wanted a letter counter live lawyer would be horrible for something like that you could do it but it would be slower and annoying it

00:24:33 would kind of look bad so there's some times that you really want JavaScript and one big time is like reactive input elements like tags or multi selects or date pickers stuff like that so this is uh so strap yourselves in let me make sure this all still works and I didn't just ruin everything okay so new bark here so let's just wipe this whole text area and I have an actual view component called bark input so view j/s refresh and so this component just kind of shows up the letters counting and has a little bit of

00:25:06 implicit validation cool that's fine but it's not linked up yet so how do we link it up anything that you can v-model you can wire model so live wire is intelligent it knows and when it finds a view component it ignores the changes in the view component and it just listens for those view input events and paths is valued down so anything that you can v-model feel free to wire model and now we have something that it's working both ways so it's view and live where they're both talking to each other and it's kind

00:25:33 of like a have-your-cake- and-eat-it-too type thing cool all right so we're almost there like if we had some loading indicator like dot dot you could do wire loading and it would show whenever like the component is making a floor request so you can show loading in case there's no little blip there's no v cloak it's just hidden by default and then it'll show when you need it there's tons of other stuff there's wire pole so you can like pole like every 300 milliseconds or something or pull a specific method every so often if you

00:26:07 want to get some reactivity oh there's echo so if you wanted to use something like if you have let's say every time we created a new bark you use laravel echo to a like broadcast an event and pusher like did all its thing if you have all that like wired up already for your app livewire just works pretty much automatically so you could do echo like barks new bark and then sorry this would be in the listener and then it would fire off whatever you put here so so that's pretty cool so you can get like actual WebSocket type real-time

00:26:37 stuff if you had two people and separate parts of the world they could you know interact with each other's thing just with live wire so pretty cool magic I know all right sweet so one last thing testing right new bark test how do we test things in live wire so live wire has its own kind of testing API and it it's all just in laravel testing so there's no need to run any JavaScript anything or any browser runtime so can add new bark we say live wire test set the title to something and call a method

00:27:09 and make sure that something exists in the database run that test and bam we're passing can't add new bark if longer than 15 characters set something to really long call submit and then I added this assert C so you can see that like it's keeping track of the rendered Dom and you can assert against that rendered um so you can make like changes fake a click or something like that assert against the dumb and then assert stuff in your database and it's all like wicked fast just like any of your laravel tests so BAM you could actually

00:27:35 TDD components like really nice with this sweet so cool we're getting there that's a that's basically that is the basics of livewire right there so livewire is out live we're framework calm let's not live yet library frameworks calm exists and all the docs are up so you can check them out there's so much I didn't go over there spa mode like with turbo links you can basically make like this weird SP a thing that that you can just have all those right route live wires and it's all like SP a feeling there's all sorts of stuff

00:28:06 transitions testing stuff nesting events validation loading states all that good stuff so give that a check out if you care and are we ready to do it let's go back to the slides okay we won hurray we wrote one end point for you know just to load the page instead of all these Ajax end points that you have to write API test for and then maybe contract test for your jest tests that rely on mocks and all that stuff and then you get mock drift so enough to do any of that just one end point zero loading States we

00:28:37 never wrote this dot loading I didn't show you the wire loading but you would use that and instead of that zero millisecond build time builds just just like that you don't even have to refresh most of the time and nine point six kilobytes of JavaScript and that's the whole bit of JavaScript that you need to make it all happen and fast simple tests which I dearly love and so it's V zero point one it's not a 1.0 yet I have like eighty five people in the repository right now and we're all going we're all

00:29:05 using it and we're finding bugs and fixing stuff but it's not necessarily ready for primetime yet so get into the repo try using it in your projects see you know see what happens submit issues and we can make this thing something viable alright let's just do it let's hit the red button I wish there was a red button well it's kind of red all right so the danger zone make public dev tools I'm sorry I I don't understand does someone else understand okay is that it did it do it make private it did it hey that's it go

00:29:57 forth make livewire things thank you you


Highlights

0:26 ๐Ÿš€ Caleb introduces himself and mentions his social media handles.
1:18 ๐Ÿ—’๏ธ He talks about his previous talk on โ€œEmbrace the Back Endโ€ and how his perspective has changed since then.
3:43 ๐Ÿ“ Caleb explains how he discovered Phoenix Live View and got inspired to create Livewire.
7:55 ๐Ÿ’ก He highlights the advantages of using Livewire, such as simplicity, access to Laravel features, and fast and stable tests.
11:17 ๐ŸŒ Caleb mentions other frameworks that follow a similar concept to Livewire, including Turbolinks and Intercooler.
13:02 ๐Ÿ“ˆ He explains the benefits of keeping the templating in the back end instead of relying on front-end frameworks.
15:08 ๐Ÿ’ป Caleb demonstrates the usage of Livewire with a basic Laravel application.
21:22 ๐Ÿ”„ He shows how to nest Livewire components and use events to communicate between them.
24:10 ๐Ÿงช Caleb explains how to test Livewire components using Laravel testing.
26:05 ๐Ÿ”ด He concludes the talk and encourages viewers to try out Livewire.

Key Insights

๐Ÿš€ Livewire combines the productivity of front-end frameworks with the server-side rendering of back-end frameworks, offering a simpler workflow without the need for complex build tools.
๐Ÿ’ก By keeping the templating in the back end, Livewire provides access to Laravel features, such as configuration files and helpers, and allows for fast and stable tests using Laravelโ€™s testing framework.
๐ŸŒ Livewire is part of a growing trend of frameworks, like Turbolinks and Intercooler, that challenge the dominance of front-end JavaScript frameworks by emphasizing server-side rendering and reducing JavaScript complexity.
๐Ÿ“ˆ The concept of keeping the templating in the back end allows for better productivity, as it eliminates the need for complex front-end build tools and reduces the reliance on JavaScript for rendering HTML.
๐Ÿ’ป Livewire simplifies the development process by providing a familiar syntax for building components using Blade templates, and by seamlessly integrating with Laravelโ€™s ecosystem.
๐Ÿ”„ Livewire components can be nested and communicate with each other using events, enabling developers to create complex UI interactions while maintaining the benefits of server-side rendering.
๐Ÿงช Testing Livewire components is straightforward using Laravelโ€™s testing framework, allowing for fast and reliable tests that cover both the front-end and back-end code.