Best code snippets, tutorials and more

Coursecomp is your starting point for developing and maintaining your web application.

How to use grouping for Routes in Laravel

In this recent addition in Laravel (since version 8.8), you can use a route controller group instead of using the controller in each route in your routes/web.php file. See the example below: Enjoy!

How to get IDs from a collection in Laravel

You can always retrieve IDs from Eloquent Collection in Laravel with the built-in method modelKeys: As the official documentation says, the modelKeys method returns the primary keys for all models in the collection

How to use Blade directives conditionally in Laravel

If you need to apply some css classes conditionally in your Laravel Blade templates, you can do it with the following technique: In this example we’ve created a table with different background for odd and even rows using Tailwind CSS classes.

How to force eager load in Laravel

You can force your app to eager load in Laravel using this method in the Service Provider. This code will throw an exception if you don’t eager load a relationship (except in production).

How to set random datetime in MySQL

Imagine you have to mass insert or update the values in your created_at or updated_at fields. You can easily achieve that with the following SQL query: You can also choose the spread in seconds, 3600 is 1 hour, 86400 is 1 day, 31536000 is 1 year.

How to fix “trying to get property of non-object” with PHP8 in Laravel

If you’re tired of the error “trying to get property of non-object”, you could use an optional helper method in Laravel. Also, if you’re using PHP8+ you could find the better way of dealing with these issues with the nullsafe operator. Here we go: You can read the official PHP reference on this operator here […]

How to make a sitemap.xml with Laravel

Let’s try to make a simple sitemap.xml for you Laravel application. You could also use the Spatie’s Laravel sitemap package, but it could be an overkill if you need just a simple sitemap for your website. First, we star with creating a Controller: In the controller we write this code (assuming you have categories, posts […]