Courses

PHP for Laravel Developers

Override/Extend Functions of Laravel Packages

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Demonstrate methods to modify package behavior
- Learn techniques for extending package classes
- Understand how to override relationship methods
- Explore creating custom models that extend package models

Let's get a bit more practical. Quite often, you want to use a Laravel package but slightly change its functionality. You can't edit anything in /vendor because package updates would wipe out your changes, right? So, I will show you what to do, with two examples.


Example 1: Override Relationship Method

Here's a situation we had at our own Laravel Daily. We're using the spatie/laravel-tags package, which is configured by just adding a Trait to our Model:

app/Models/Course.php:

use Spatie\Tags\HasTags;
 
// ...
 
class Course extends Model
{
use HasTags;
 
// ...

Inside that trait, there's a polymorphic relation method:

vendor/spatie/laravel-tags/src/HasTags.php:

trait HasTags {
// ...
 
public function tags(): MorphToMany
{
return $this
->morphToMany(self::getTagClassName(), $this->getTaggableMorphName())
->using($this->getPivotModelClassName())
->ordered();
}
}

But what we needed in our project was to automatically...

The full lesson is only for Premium Members.
Want to access all 16 text lessons of this course? (52 min read)

You also get:

  • 77 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord