Is it possible to override the with method of Laravel?

3

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!']);

Could it be in App\Http\Controllers\Controller.php override with , or even somewhere outside the Vendor directory?

For example, I'd like to override for:

//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 this in the controller would suffice:

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

Now to get the above result I'm forced to do so:

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

1 answer

2

No, you can not override this method in this way, but there is something that can be done in the Controller class that will serve as the basis for all controllers that inherits 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 some controller :

<?php namespace App\Http\Controllers;

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

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

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

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

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

Steps:

Create a folder Helpers within the app folder of the project . In it, create a file named 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 can not be equal to what already exists, so redirect_with has been 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, needs to register in composer.json like this:

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

You now have a key files with the address of your new function code ( helpers ).

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

Its use becomes simple from here:

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

It's an easy way that does not compromise . The big problem in doing rewriting on methods of Core and time of package updates that will all be lost by new versions downloaded, creating Core functions would be the best way to solve your problem .

    
10.11.2016 / 13:41