Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding a trait method in Laravel controller

I cannot override a method of a trait in my Controller class. Here is an example of my trait method:

protected function resetPassword($user, $password)
{
    $user->password = bcrypt($password);

    $user->save();

    Auth::login($user);
}

And here is my Controller:

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;

use Illuminate\Foundation\Auth\ResetsPasswords;


class PasswordController extends Controller
{
    use ResetsPasswords {
        resetPassword as newReset;
    }

    /**
     * Create a new password controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    protected function resetPassword($user, $password)
    {

    }
}

I found one example, but I am not sure that I am on a right way.

like image 932
Tomas Bajoras Avatar asked Jun 10 '16 06:06

Tomas Bajoras


1 Answers

As you have already done it yourself, you need to alias framework trait's resetPassword method and then implement your own:

namespace App\Http\Controllers\Auth;

use Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;

class PasswordController extends Controller
{
    use ResetsPasswords {
        resetPassword as frameworkResetPassword;
    }

    protected function resetPassword($user, $password)
    {
        // Do your custom password reset logic here
        $user->password = bcrypt($password);
        $user->save();
        Auth::login($user);

        // Then you can pass the work over to framework's implementation
        // if that's needed.
        // $this->frameworkResetPassword($user, $password);
    }
}

By the way, Laravel's own password reset functionality supports logging users in.

like image 63
sepehr Avatar answered Oct 13 '22 18:10

sepehr