Home > Mobile >  Override protected method in Laravel Illuminate class
Override protected method in Laravel Illuminate class

Time:07-08

I'd like to override the following method in Laravel's Illuminate\Foundation\Vite class:

    /**
     * Generate a script tag for the given URL.
     *
     * @param  string  $url
     * @return string
     */
    protected function makeScriptTag($url)
    {
        return sprintf('<script type="module" src="%s"></script>', $url);
    }

...by adding a "defer" attribute to the script tag. How would I go about doing this, as this is a protected function?

CodePudding user response:

May be like that :

<?php
namespace myApp;
use Illuminate\Foundation\Vite as IllVite;

class myClass extends IllVite{
//...
protected function makeScriptTag($url){
    return sprintf('<script type="module" src="%s" defer></script>', $url);
}

//...
}

In the controller(s) which call "Vite", change :

use Illuminate\Foundation\Vite;

by

use myApp\myClass;

CodePudding user response:

The svgta is right, if you use that method in another place in your app.

But, if you want to change only that particular behavior, and not to use it in other places, then you can rewrite the original class and replace it by binding changed class to the app in app/Providers/AppServiceProvider:

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(
            'Illuminate\Foundation\Vite', // original class that will be replaced
            'App\VendorRewrites\ViteChanged' // custom class that will be injected
        );
    }
............

Another post that can help: Laravel 6-7 How Can I Override/Change a Vendor Class?

  • Related