Skip to content

Instantly share code, notes, and snippets.

@nasrulhazim
Last active May 20, 2021 11:41
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nasrulhazim/4b78409e098440a6bde17254b6e882fd to your computer and use it in GitHub Desktop.
Save nasrulhazim/4b78409e098440a6bde17254b6e882fd to your computer and use it in GitHub Desktop.
Laravel: Forgot Password Controller for API
<?php
Route::post('forgot/password', 'ForgotPasswordController')->name('forgot.password')
<?php
namespace App\Http\Controllers\Api\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
use Illuminate\Support\Facades\Password;
class ForgotPasswordController extends Controller
{
use SendsPasswordResetEmails;
/**
* Create a new controller instance.
*/
public function __construct()
{
$this->middleware('guest');
}
public function __invoke(Request $request)
{
$this->validateEmail($request);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$response = $this->broker()->sendResetLink(
$request->only('email')
);
return $response == Password::RESET_LINK_SENT
? response()->json(['message' => 'Reset link sent to your email.', 'status' => true], 201)
: response()->json(['message' => 'Unable to send reset link', 'status' => false], 401);
}
}
@afrazahmmad
Copy link

We must handle request and guess expected response type if same function is returning response for both WEB and API like this

if($request->expectsJson()){
        return $response = Password::RESET_LINK_SENT
            ? response()->json(['status' => 'Success','message' => 'Reset Password Link Sent'],201)
            : response()->json(['status' => 'Fail','message' => 'Reset Link Could Not Be Sent'],401);
    } 

@mouradev
Copy link

In the route action i had to add ‘Api\Auth’ before the ‘ForgotPasswordController’. Thanks!

@joerecra
Copy link

Why did I get Route [password.reset] not defined ??? If I'm using a api request no form action in blade template. Anyone knows how to resolve this ?

@AndyDunn
Copy link

@joerecra You might have to run the 'php artisan make:auth' command.

@MisterFredy
Copy link

and for mobile development how we catch link for that?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment