Laravel Serializable Closure: serialize the unserializable
PHP doesn’t let you serialize closures, but Laravel does, thanks to an underrated package that’s built into the framework. I show you exactly how Laravel serializable-closure works, how Laravel uses it internally, and how you can use it safely (and securely!) in your own projects.
Everything I said
PHP as a language does not allow you to serialize a closure. But thanks to this very underrated Laravel package, you can actually serialize closures. Laravel Serializable Closure.
This is a free and open source package provided by the Laravel team itself, and if we check out the About over here, it says it provides an easy and secure way to serialize closures in PHP. What does that even mean? I promise we're gonna get there, but first, credit where credit is due. This is a fork of an older package, and this older package was being completely rewritten to be an FFI extension, and FFI is not enabled by default in web requests.
So that was gonna create a pretty big barrier to, like, running Laravel. And so the Laravel team decided, "We will fork it. We will fork it, and we'll maintain this other version that is not an FFI version." So thanks to the original team that wrote this. Now, should you install this into your application? Absolutely not, but not because it's not useful, but because it's already there.
So if we look at Laravel/Framework, and we come down here to Composer, and then we come down here to Laravel Serializable Closure. So when you install Laravel the framework, you get Laravel Serializable Closure, and that's because the framework relies on it a lot. I'm first going to show you how you can use it for whatever you might need it for, and then we'll dive into where the framework uses it, and that might spark some ideas for
you. But before we do that, I need to thank the sponsor for this episode, and that is Bento. Bento is a marketing and transactional email provider. I use it for all of my stuff. I use it for my personal email newsletter. I use it for our business to send out transactional and marketing emails. If you need an email provider for your business, I would highly encourage you to check out Bento at bentonow.com.
It is a great product with even better support. So if you're worried about landing in people's inboxes or getting blacklisted by Gmail, I highly encourage you to go sign up for Bento, talk to their support team. Turns out the support team is just the founder most of the time, which is super awesome. Check out Bento at bentonow.com and tell them that I sent you.
Okay, let's get back to Laravel. I have a sample command right here, and this is where we're going to work. So first, let me demonstrate the problem. Closure equals function echo, "Hey." So this is a closure, right? And if I were to try to serialize the closure, and then we run this with PHP Artisan and then T for test, it's gonna say, "Serialization of closure is not allowed." This is PHP saying, "I can't do that." What is serialization?
That is a good question. Let's change this to array, and we'll say array is A is one and B is two. So if we say A is one, B is two, and then we serialize the array, and let's just echo that out, and we'll run this again. You'll see it puts this out. Eh, it puts out a... It's kinda weird, but that is the serialized representation of the array that we passed in.
Okay? And what you can do with that is you can say serialized equals that, and then you can, let's say, put that in the queue or pass that over the wire to somewhere else. Or, you know, let's say, um, let's say you're writing a cache driver or something.
You could put this in the cache, and then when it, uh, when you're pulling it out of the cache driver, what you would do is you would do unserialize serialize, and let's renamed th- rename this to serialized, and we'll say unserialized equals that. And let's just dump out unserialized now.
So we've gone, uh, from array to a serialized version, and then we've unserialized it, and if we ran this again, boom, it just comes right back to life. So serialization is a way to generate a universally storable representation of some variable in PHP. In fact, if we look at the PHP docs on serialize, it says, "Generate a storable representation of a value.
Useful for storing or passing PHP values around without losing their type and their structure. To make the serialized string into PHP again, use unserialize." Okay, so that is, um... We could also... I can show you just one other format. And so if we were to dump serialized again and then come back here, you'll see, look, it says it's a standard class, um, and here are all the, uh, the members of that class
in there. So this is a way to turn a structure into a string and then rehydrate it later. You can think of it as dehydration, rehydration. The problem comes when you're trying to serialize a closure. You're not allowed to do it, right? And you might wanna serialize a closure to put it in the queue because remember, with Laravel, we can queue closures.
We can schedule closures. But how does Laravel do it? Seriable closure. Okay, so a serializable closure, um, let's do it like this. Let's do serializable closure, and we're going to make an unsigned serializable closure. This is the non-secure version.
So if you are passing, um, if you're passing some sort of, uh- Uh, some sort of payload that needs to be secured, you would want to sign it with a secret, such that when you unserialize it on the other side, you have to have that same secret. We'll do that in a second. But for now, we're gonna serialize this closure. And so if I say, um, serializable, it's kind of hard to say.
Serializable, and then we dump this out. What does serializable look like? Uh, it's gonna be a class. Here we go. It is an unsigned serializable closure. The, um, serializable is, here's our closure right here, and then it keeps, it keeps some other information around.
So all we've done so far is we've passed our closure into this Laravel class. Now, the interesting part comes right here. If we were to say serialize, serialize, I think that's right, serialize the serializable, and we run that, look at that. We've serialized a closure.
In fact, we really haven't. We've serialized a class that inside of it contains the closure, and look, echo, "Hey." That's what we wrote. That is the stuff we wrote. It gets even cooler if we were to say A equals hey, use A, echo A.
Now, if we were to serialize that, this is where the magic comes in. Um, Laravel looks at this and says, "Okay, well, we gotta, we gotta serialize those variables," because the inner scope, that closure, is pulling in a variable from the outer scope. That's what this use statement does. This says, "Hey, I know that A is outside.
Why don't you bring that guy inside, 'cause I'm gonna use it?" And it says, "Whoops, looks like we need to get A, and the value is hey, and we need to store that, such that when we unserialize it on the other side, we've got all the right information." Now, how do we get this, uh, how do we get this closure to come back to life, okay? So, we've serialized it.
We've serialized it, serialized. We've serialized it. We've put it on the queue. We've sent it over the wire to some other part of our application, maybe. We've put it in cache, and it's been, you know, stored for forever, and now it's being rehydrated, and we wanna bring it back to life, okay? What are we gonna do? Well, we are going to first, uh, unserialize equals unserialize the serialized.
It's just a hard video to record with all these words. Serialized. Serialized. All right. So we are going to dump the unserialized version, okay? So let me, um, echo, let's just use this line, serialized is that, and then we can dump the unserialized, and let's run this.
Let's get some space, and here we go. Okay. Look at this. All right. Serialized. It is an object of 55 characters, a serializable closure. There's all the information. Now, unserialized, it has come back to life as a proper class, right?
So it has come back to life as an unserializable, or, I'm sorry, an unsigned serializable closure. If we were to type, uh, type hint this, unsigned serializable closure, what do we get off of here? We get a get closure. This is our original thing that we serialized. We turned into a string.
So now if we dump that, let's get rid of this guy, 'cause it's taking up a lot of space. So now if we dump that, we're gonna see, boy, there's a closure, and it uses A. Yeah. That feels right. So, if we say closure equals that, and we can, uh, we can just call user func. Why not? Call user func closure.
Are we gonna see echo, "Hey"? We have successfully serialized the unserializable, thanks to Laravel's serializable closure. Pretty freaking cool, right? I'm gonna show you, uh, I'm gonna show you some places in the Laravel framework where they're using the serializable closure, and then I'm gonna show you how to sign your serializable closure.
So, in our case, we used an unsigned serializable closure, which means we serialized it, and then we woke it up, and we just ran the code that we woke up, which, in some cases, is fine. If you've got chain of custody all the way through, and you're never passing your payload outside or anything like that, that's totally fine. But if you need an extra step of security, we can sign that closure, such that when it wakes back up, we're guaranteed that it is the same code
that went to sleep, because we have a signature on there. But first, let's look at some places that the Laravel framework uses serializable closures. Let's go spelunking, and so first thing we're gonna do is we're gonna right click on serializable closure and say Find Usages. And this is gonna find all the places that this class is being used, and what we wanna focus on is interesting stuff.
Unlike our test command, we wanna focus on interesting stuff down in the framework itself. So it looks like, um, it looks like here in routing, let's go, um, let's do missing. So if we come down here into missing, it's, uh, this is in the prepare for ser- serialization part. So when you, uh, have a production Laravel application, you can cache your routes, and that turns it into one big serialized file that is super fast to look up.
There are two places where you are allowed to use a callback for, uh, part of your route. One of them is the missing callback. So if a route model is not found, there is a missing callback that'll let, that allows you to control the behavior. That's a callback. That's a closure. And so instead of, uh, instead of disallowing that or saying, "Hey, you can't cache routes if you use that," they just wrap it up in a serializable closure and then serialize that.
Let's look at another one. I wanna look, I wanna look for the queue. So if we go to new instance creation. All right. Look down here. This is great. Call queued closure, bus, pending chain. Um, okay, so we have a lot. Pending batch. Let's look at, let's look at the queue called queued closure.
There we go. So, um, when you have a queued closure, when you, uh, are passing a closure onto the queue, it gets turned into a serializable closure, and that is because those can go, those can be turned into strings and go into whatever queue driver that you're using. Let's look at one more use case, and I think this one we can look in, so new instance creation, bus, pending batch.
That's probably fine. Um, let's look at... I think we just did that one. So you can see they use it, they use it all over the place. Let's look at pending batch before. Um, pending batch before uses a serializable closure right here. So this is checking to see, hey, they're going to pass me a callback.
The callback could be a closure, and if it is a closure, we need to turn it into a serializable closure. If it's just an array of like, you know, a podcast job, class, handle, or something like that, that's fine. That's serializable on its own. We don't have to serialize that. But you can see when it is a callback, they use that serializable closure.
All right, the last thing I'm gonna show you on this excellent library is how to sign your closure. So if this, uh, serialized value ever leaves your control, you don't want people just, like, modifying the code to do nefarious things, right? So we can sign the serialized value, and then when we unserialize it, that signature will be checked to make sure nobody has tampered with it.
When we first created our serializable closure, we explicitly said we wanted an unsigned one, which is fine in most cases. But if we were to new up a serializable closure, it's going to pick between signed and unsigned, and the way that it picks is, is there a signer? And we can set a signer by setting the secret key. So if we want to secure our payloads because we lose control of them at some point, we can do that.
Serializable closure, set secret key, my super secret key. Don't use that. And instead of unsigned, we'll just new it up, and then let's DD the serialized version out here and say, there we go. So, with this, we get something new. We get a hash that has a computed signature in here.
Now, imagine, use your imagination because this is not true. Imagine I'm a bad guy, right? Imagine I've just man in the middled you, or you passed your payload over to me for safekeeping, and I thought, "You know what? I'm gonna muck it up. I'm gonna change everything." Serialized equals this string that I stole from you.
We don't need you guys anymore. You've given me a serialized payload. I've looked at it and said, "I'm gonna mess up your whole life, and I'm gonna change something, and then give it back to you, and you're gonna run it on your machine, and now I'm in charge." We don't like that, right? So, um, if we take this string, we should still be able to unserialize it because we haven't changed anything, right?
So if we, um, we're no longer serializing it. I commented that out. We are taking the serialized value, and we're gonna unserialize it. And if we just, uh, unserialize, and we'll clear this out and run it again, and it looks like, yeah, that worked just fine. Now, if I change something, if I change hey to be foo, what is going to happen?
Thank God, nothing. Nothing is going to happen. Your closure might have been modified or it's unsafe. That is very true. So whenever, whenever you need, um, integrity of that closure, and that is when you're passing it outside your control, right? Maybe you're passing it over the wire to another service.
Maybe you're putting it in storage that you don't actually control. It's a good idea to sign it, and then when it comes back to life, that signature will be verified, and if it's been tampered with, it's not going to run. Now, in our case, all we did is we changed hey to foo. So if we run this again, it should be, yeah, we're back to normal.
But you can imagine, you can imagine somebody comes in here and they just write, uh, they just write exec, and now inside of your closure, they, they have root access. They can do whatever they want. They can remove your whole directory. They can phone home. They can... They basically just, they own your system now. So, um, signing a closure like this can be really useful in certain circumstances.
You'll see throughout the framework that they don't sign them all the time, often because they're staying within our control, and we're not passing them out to a third party. That is Laravel serializable closure, one of the unsung heroes of the ecosystem. I have more videos on different parts of the ecosystem. If you wanna check out a video on Laravel Dusk, I will add that here at the end.
This is an entire series, so check out the whole playlist. And until the next time, see ya.