adxmcollins's avatar

Best way to store code snippets in Laravel (database, storage engine, etc)

Hey everyone,

I tried to search for a discussion on this topic in the forum but was really struggling to find something along the lines of what I am trying to achieve.

Basically, I am working on a small project that should be able to save snippets of code in all sorts of different languages. I am wondering what the general consensus in on how to store this; generally and specific to Laravel if there's a recommended Laravel method.

As an example, a user may save a PHP code snippet against their account which they can view/retrieve later. It would need to retain any formatting as the frontend provides a code editor using the Ace open source editor (ace.c9.io).

I have thought about: storing in the database using base64/similar or creating and storing in flat files in the storage engine (.txt maybe) and referencing the file in the database.

That said, I am open to other ideas! Thanks in advance.

0 likes
6 replies
James_Moore's avatar
Level 14

Hey @adxmcollins

https://laracasts.com/series/how-do-i/episodes/13 Two parts Jeffery creates a similar application.

In your scripts or snippets table migration, the following should work fine. $table->text('body');

Then check out


    <div class="card-body">
        <pre class="p-2"><code>{{$snippet->body}}</code></pre>
    </div>

I believe the classes are just bootstrap css, I made a similar project a while back that I never finished. https://github.com/James-N-M/script-snips

adxmcollins's avatar

Hey @james_moore, thanks for those couple of links and the information!

I'll have a look and see what I can get working based on that.

1 like
atif56's avatar

Hey @adxmcollins just wondered if you got anywhere with this project and what method you used to do this? Am working on a similar side project and am having the same debate on my head on how best to store PHP/ JS code snippets and then how best to display them whilst being safe as potentially anyone will be able to do this on my site. Cheers

adxmcollins's avatar

@atif56 I went with the above suggestion and just stored it in the database. The similar application Jeffery created also helped me on a few decisions for how to build the app!

Snapey's avatar

@atif56 at the end of the day these are just ascii snippets. The highlighting is done when displaying the snippet, not before storing it. You might need to ask the user what language it is and save that alongside the snippet

As long as you never echo the snippet to the screen without first escaping it then you should be safe

1 like

Please or to participate in this conversation.