Best code snippets, tutorials and more

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

How to include javascript files on specific pages with Blade in Laravel

There is a beautiful trick to make this happen with Laravel. First, you need to specify @stack method in your main blade file (the wrapper) or in the file for javascript includes. Second, you need to “push” from your specific page the needed javascript include. For example, we have this blade files structure: /views/main.blade.php, the […]

How to add index to an existing column in Laravel

If you want to add a new index to some columns in your existing table, you can do it pretty easily with Laravel migration. First, create the migration: Then edit the migration php file. In this example, we are adding two indexes to a table, parent_id and slug:

How to upgrade Laravel to latest minor version?

If you want to upgrade Laravel to latest minor, for example, from 9.5 to 9.6, changing the version of composer.json file won’t help (assuming you run composer install afterwards). You should run composer update instead. Let’s see the current version before the update: Now let’s update the framework:

How to check the migration before running it in Laravel

Hello, friends. In Laravel you can check the queries which your migration will run before actually running it. This is called a “dry run”. You will have to use –pretend flag for that. See the example below: First, we create a migration: Now, let’s go and edit the migration, for example: Now we can “pretend” […]

How to query belongsToMany relationships in Laravel

Suppose we have Posts which belong to many different Categories. For this purpose we make three DB tables: posts (id, title), categories (id, name), and an intermediate one (posts_categories, with columns post_id and category_id). The Post Model should be: The Category Controller: You can also return posts collection with dynamic parameters:

How to comment the code in VSCode editor

MacOS users The easiest way to add or remove selection comment would be ⌘/, but you can also use these keyboard shortcuts: ⌘K ⌘C Add line comment⌘K ⌘U Remove line comment⌘/ Toggle line comment⇧⌥A Toggle block comment See the full list of keyboard commands for VSCode on MacOS. Windows users Ctrl+K Ctrl+C Add line commentCtrl+K […]

How to flatten a collection in Laravel

Here is a cool trick with the flatten method, which can convert your multi-dimensional Laravel collection into a flattened (single dimension) one. See the code below: