DEV Community

Abanoub Hanna
Abanoub Hanna

Posted on • Updated on • Originally published at abanoubhanna.com

convert old('d') to $model->d in Laravel using regular expressions (RegEx)

While developing a website in PHP Laravel, I reused create.blade.php as edit.blade.php. So I need to edit some things, especially the input values.

In create.blade.php we use old('something') to retain the current <input> value by the user.

But in edit.blade.php we use $model->something to get the <input> value from the project backend.

So, I need to convert every old() to $model. But I am too lazy to rewrite all of them manually.

I used regular expressions (RegEx) to automate that replacement / conversion.

I used this old\('(\w+)'\) to select all of those old('something'), then I added $product->$1 to replace all selected to $product->something.

Steps to use RegEx in VS Code

In Visual Studio Code, press CMD + F (Mac OS) or Ctrl + F (Windows or Linux). You'll see an input box in the top right corner. write the RegEx in it to select them. Make sure you have pressed the .* button as it indicates the usage of regular expressions. Then click on the arrow on the left side of the input box, which is like >. After clicking on that arrow, another input box will appear below the current one. Write the RegEx to replace the selected statements or text.

You can click the button to replace the current selected one, or click on replace all to convert all selected statements at once.

RegEx code explained

old \(  '   ( \w+ )   '   \)
old (   '   material    '   )
Enter fullscreen mode Exit fullscreen mode

In RegEx, we use \( to select literal ( not the meaning of brackets in regular expressions. It is the case in using \) too.

We use \w+ to select all text content with English letters only. So, RegEx will select the text until it finds any other character. In our case, it selects until it reaches ' character.

The brackets () around \w+ are not escaped – as you can see in code – because want their semantic meaning in regular expressions. We do not want a literal brackets. Their meaning in RegEx is to capture the content in a variable. The variable in our case is $1 as it is our first selected range.

There is $0 but it is a story for another time.

use RegEx to replace all old with $model in Laravel in VS Code

Watch this short video for more clarity. I hope this helps. Share if you care.

Follow me to get notified of new posts I create here on my blog. Follow me on Twitter @abanoubha. Follow me on LinkedIn. Join my Telegram channel @softwarepharaoh. Follow my Facebook page @softwarepharaoh.

Top comments (0)