php – Would it be possible to override Laravel's with method?

Question:

In parts of my application I'm using the following redirect :

return redirect('/painel/posts')
        ->with(['error' => 'Ocorreu um erro ao tentar adicionar o post!']);

Would it be possible in App\Http\Controllers\Controller.php overwrite with , or even somewhere else outside the Vendor directory?

For example, I would like to overwrite to:

//Illuminate\Http\RedirectResponse
public function with($key, $value = null)
{
    //$key = is_array($key) ? $key : [$key => $value];

    $key = ['status' => $key, 'mensagem' => $value];

    foreach ($key as $k => $v) {
        $this->session->flash($k, $v);
    }

    return $this;
}

With that in the controller it would be enough:

return redirect('/painel/posts')
        ->with('error','Ocorreu um erro ao tentar adicionar o post!');

In the view it would look like this:

@if (session('status'))
    <div class="alert alert-{{ session('status') }}">
        <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
        {{ session('mensagem') }}
    </div>
@endif

Because currently, to obtain the above result, I am obliged to do this:

return redirect('/painel/posts')
        ->with([
                 'status' => 'error',
                'mensagem' => 'Ocorreu um erro ao tentar adicionar o post!'
               ]);

Answer:

No, you can't override this method that way, but there's something you can do in the Controller class that will serve as the basis for all controllers that inherit its behavior:

<?php namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
use Illuminate\Support\Facades\View;

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

    public function with($status, $message)
    {
        request()->session()->flash('status', $status);
        request()->session()->flash('message', $message);
    }
}

Using in some controller :

<?php namespace App\Http\Controllers;

class SavePictureController extends Controller
{
    public function index()
    {
        $this->with('status', 'message');
        return view('pictures');
    }
}

Explanation: the line redirect('/painel/posts')->with() in the with is a Session Flash and for this to work and have the same behavior you have to use:

request()->session()->flash('status', $status);

In is complicated to rewrite methods, especially when they are part of the core of it is already ready like this and there is no way to go to the classe and simply write another method right below, there is no overload in PHP and the rewriting being done with an inheritance can break the Laravel structure.

The only simpler, objective, and trouble-free way is to create a helper by calling that other helper redirect .


Steps:

Create a Helpers folder inside the app folder of the project. In it create a file called helpers.php in your content:

<?php

if (!function_exists('redirect_with'))
{
    function redirect_with($url, $status, $message)
    {
        return redirect($url)->with(['error' => $status,
            'message' => $message]);
    }
}

note that the name cannot be the same as what already exists, so redirect_with was placed. Note: You can create as many functions as needed within this helpers.php file.

The application has to know that this helpers.php file exists, it needs to register in composer.json like this:

"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files":[
        "app/Helpers/helpers.php"
    ]
},

you now have a files key with the address of your new helpers code.

At the command prompt type: php.exe composer.phar dump , with this command it will register in your application's auto_load.php .

Its use becomes simple from there:

return redirect_with('/painel/posts',
                     'error',
                     'Ocorreu um erro ao tentar adicionar o post!');

It's an easy way that doesn't compromise the Core codes. The big problem in doing rewrites in Core methods and when updating packages that will all be lost by new downloaded versions, creating wrapper functions would be the best way to solve your problem .

Scroll to Top