Best code snippets, tutorials and more

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

How to set timeouts when working with API in Laravel

When you’re working with third-party platform APIs that aren’t very stable, you can make use of some built-in methods on the HTTP client to do some error handling. For example, if you’re making requests to some website API, but the server is slow or there’s an issue with connectivity, you can add a timeout method […]

Adding estimated time to read an article in Laravel

If you’re wondering how to do that, the short answer is here: we are going to use one private method and Laravel Accessor. Don’t be afraid, it’s pretty simple. First off, we’re going to count seconds and minutes to read using this formula: Let’s make a whole function using that formula and put in into […]

How to pass a Model instance to Livewire in Laravel

If you want to pass a Model to your Laravel Livewire component, you can do it via public property instead of adding the code to the mount() method. Take a look at this code excerpt: By @sky_0xs

How to use default Models with relationships in Laravel

As you may know, you can skip checking if your relationship doesn’t exist in Laravel with withDefault method. But did you know that you can also assign attributes to a default Model? See the example below:

How to use a relationship in Laravel Accessor

Imagine, you have to use a relation within your Model Accessor. Let’s see our Post Model example: As you see, we reference the relation with this code – $this->platform->name. Don’t forget that you have to “camel case” seoTitle for your accessor method name, and use it as a “snake case” seo_title in your Blade file […]

How to write a route that returns only a view in Laravel

You can write a route that only returns a view in your routes/web.php using the Route::view method instead of closure function inside the Route:get method. See the example below: You can also pass additional data to the view with this method:

How to update dev dependencies in NPM?

If you have installed new Node.js packages and want to update your package.json file locally to these new versions, you have to install npm-check-updates package globally: Then you have to run this command: As a result, you will see the following screen (the list of packages is only for example): The final step is to […]

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