knubbe
knubbe

Reputation: 1182

How to share one method to all controllers in Laravel?

How to share one method to all controllers with different DI, view and parameters? I need something like this:

public function method(Model $model)
    {
        $baseData = [
            'model' => $model,
            'route' => route('$route', [$param => $model]),
        ];

        return view($view);
    }

Upvotes: 6

Views: 9018

Answers (2)

Salim Djerbouh
Salim Djerbouh

Reputation: 11064

All controllers extend App\Http\Controllers\Controller so you can just place it there

<?php

namespace App\Http\Controllers;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function method(Model $model, $route, $param, $view)
    {
        // Declared but not used
        $baseData = [
            'model' => $model,
            'route' => route($route, [$param => $model]),
        ];

        return view($view);
    }
}

And use it with $this->method()

For example in HomeController

<?php

namespace App\Http\Controllers;

use App\User;

class HomeController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        $user = User::first();
        return $this->method($user, 'home', 'user', 'welcome');
    }
}

Now accessing domain.tld/home will return the welcome view

Upvotes: 23

Nitesh Mangla
Nitesh Mangla

Reputation: 119

If you want to share function to all controller best way will make service in service folder of app. step to make service:-

1.create service using artisan command php artisan make:service service_name and define function that to share to all controller in your project.

  1. after making service your have to register this service with provider.make a provider using artisan command. php artisan make provider:provider_name and you will see 2 function register and boot register function is used to register your created service and boot for call already register service

register service like this

public function register()
    {
         $this->app->bind('App\Services\servicename', function( $app ){
            return new serviceclassname;
        });
    }

3.Go config folder ,open app.php where you will get providers array. In this provider you have to define you provider like App\Providers\providerclassname::class,

  1. call this service in controllers like use App\Services\serviceclassname;

public function functionname(serviceclassname serviceobject)
{
  serviceobject->functionname();
}

Upvotes: 2

Related Questions