PHP code example of claudye / laravel-hooks

1. Go to this page and download the library: Download claudye/laravel-hooks library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

claudye / laravel-hooks example snippets


namespace App\Http\Controllers;

use LaravelHooks\Traits\HasControllerHooks;
use Illuminate\Http\Request;

class ExampleController extends Controller
{
    use HasControllerHooks;

    public function index(Request $request)
    {
        // Your logic here.
        return [
            "users" => $this->queryBuilder->all()
        ];
    }

    public function show(Request $request)
    {
        // Your logic here.
        return [
            "user" => $user
        ];
    }

    /**
     * Defines hooks for methods in the controller.
     */
    public function useHooks()
    {
        // Register a before hook for the 'index' method
        $this->beforeCalling(['index', 'show'], function ($request,...$parameters, $method) {
            
            $this->queryBuilder->filters($request->all()); 

            logger('Before calling index method');
        });

        // Register an after hook for the 'index' method
        $this->afterCalling(['index',"show","edit"], function ($request, $result,...$parameters, $method) {

            // Modify the result after the 'index' method is called
            logger('After calling index method');

            event(new SomeEvent($result))

            return response()->json([
                'data'=>$result
            ]);
        });

        // You can add other hooks as necessary.
    }
}

$this->beforeCalling(['store',"update","delete"], function ($parameter1, $parameter2,...$methodName) {
    // Modify the controller instance before executing 'store' method
    $this->someService = app(SomeService::class)->init();

    $parameter1->modify();
});