Would it be possible to override Laravel’s with method?

Asked

Viewed 388 times

3

In parts of my application I am using the following redirect:

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

It would be possible in the App\Http\Controllers\Controller.php overwrite the with, or even at another location outside the Vendor directory?

For example, I would like to overwrite 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 that in the controller:

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

The view 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

For currently to get the above result I am obliged to do so:

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

1 answer

2

No, you cannot overwrite this method in this way, but there is something that can be done in the class Controller which will serve as a basis for all controllers who inherit their 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 that 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 the Core of is already ready like this and has no way to go in classe and simply write another method down, there is no overload in PHP and the rewriting being done with an inheritance can break the structure of Laravel.

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


Footsteps:

Create a folder Helpers inside the briefcase app of the project . In it create a file called helpers.php in its contents:

<?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 equal to what already exists, so it was placed redirect_with. Observing: can create as many functions as needed within that file helpers.php.

The application has to know that this file helpers.php exists, needs to register on composer.json thus:

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

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

In the command prompt typhoon: php.exe composer.phar dump, with this command will register on auto_load.php of its application.

Its use becomes simple from there:

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

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

  • I thought about overwriting so I wouldn’t even have to use "$this->".

  • @Fabio you’re making trouble and use $this-> in PHP is normal of the architecture itself. Another thing the redirect('/painel/posts')->with returns a session flash and the only way would be this. You want to leave this pattern ?

  • I understood you, Virgilio. Let me explain, I wanted to overwrite the with, however, keep part of its behavior, I only wish instead of passing an array, passing two strings. All the rest of the behavior would be maintained. However, this superscript would have to be outside the Vendor directory. I know that originally this code is in Illuminate Http Redirectresponse;

  • Doubt: @Fabio: has how to rewrite, maybe it gives an unnecessary work, but, can be created a wrapper a code that exists called by other improved code. What would you call it? has idea?

  • You want the creation of a helper?

  • In theory, yes. In practice the intention was to call redirect('/')->with('error', 'message here'), whereas the overwritten method would take these two strings and play into an array ['status' => $string1, 'message' => $string2]

  • redirect is not a class is a function which returns the instance of classe Request, got it?

  • For a better understanding edit the question

  • @Fabio, I understood what you wanted to do, which is to tinker with Laravel’s Core, never do this, because, can mess up component upgrades. Make a helper like I told you

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.