Laravel 7 redirect issues - laravel

I'm trying to redirect with a message to a view ( notification ) after the form is successfully validated / stored and emailed.
Everything Works as expected but unable to redirect after the email is sent.
Tried redirecting after form validation and it works. But if i call the store() and try to redirect after save() it does not redirect.
I though maybe something was wrong with my store() function so i created an empty function test() and tried redirecting if like this
public function test($request){
Session::flash('message', 'alert-danger');
return Redirect::to('/notifications');
}
public function test(){
Session::flash('message', 'alert-danger');
return Redirect::to('/notifications');
}
It still does not work.
but if redirect from validator() it works fine.
I don't know what is wrong. Please help.
<?php
namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use App\Mail\RegistrationMail;
use Illuminate\Support\Facades\Mail;
use App\Register;
use Illuminate\Support\Facades\URL;
use Session;
use Illuminate\Support\Facades\Redirect;
class RegisterController extends Controller
{
protected function store(Request $request){
$length = 16;
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$code = substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
$user = new Register();
$user->fname = request('fname');
$user->mname = request('mname');
$user->lname = request('lname');
$user->email = request('email');
$user->kathum_tui = $code;
$user->created = \Carbon::now();
$vfname = request('fname');
$vlname = request('lname');
$vemail = request('email');
$url = URL::temporarySignedRoute('verify', now()->addMinutes(1500), ['fname' => $vfname ,'lname'=> $vlname , 'email'=> $vemail]);
$user->save();
Mail::to($user['email'])->send(new RegistrationMail($user,$url));
Session::flash('message', 'alert-danger');
return Redirect::to('/notifications');
}
protected function validator(Request $request)
{
$validator = Validator::make($request->all(),[
'email' => ['required', 'string', 'email', 'max:255', 'unique:registers'],
]);
if ($validator->fails()) {
$request->validate( [
'fname' => ['required', 'string', 'max:255'],
'mname' => ['nullable','string', 'max:255'],
'lname' => ['required', 'string', 'max:255'],
],
[
'fname.required' => 'First Name Cannot be empty!',
'lname.required' => 'Last Name Cannot be empty!',
'email.unique' => 'You have not completed the Registration. Please check your email to complete the Registration.',
]
);
}else{
$request->validate( [
'fname' => ['required', 'string', 'max:255'],
'mname' => ['nullable','string', 'max:255'],
'lname' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:registers'],
],
[
'fname.required' => 'First Name Cannot be empty!',
'lname.required' => 'Last Name Cannot be empty!',
'email.unique' => 'An account already Exist with this email. Forgot Password',
]
);
$this->store($request);
}
}
}

You should return your store method call in the validator function like as following:
return $this->store($request);

Related

How can I redirect to function controller after registration in laravel 8

I hope you can help me, I wanna customize the registercontroller from Laravel, I have this, but after the user is registered send me a JSON of data, how can I do for don't send me the JSON and redirect to the HomeController.
Thanks.
PD. Sorry for my English.
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => ['required', 'string', 'max:255'],
'nombre' => ['required', 'string', 'max:255','unique:users'],
'telefono' => ['required', 'numeric', 'max:99999999', 'min:00000000'],
'direccion' => ['required', 'string', 'max:255'],
'sueldo' => ['numeric','min:0.01','max:0.99'],
//'foto' => ['string', 'max:255'],
'email' => ['string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:4', 'confirmed'],
]);
if ($request->hasFile('foto')) {
$request = request();
$file = $request->file('foto');
$nom_imagen = time().".".$file->getClientOriginalExtension();
$upload_path = 'imagenes/';
$profile_image_url = $upload_path . $nom_imagen;
$success = $file->move($upload_path, $nom_imagen);
} else {
$nom_imagen = '';
}
return User::create([
'name' => $request->input('name'),
'nombre' => $request->input('nombre'),
'telefono' => $request->input('telefono'),
'direccion' => $request->input('direccion'),
'sueldo' => $request->input('sueldo'),
'email' => $request->input('email'),
'foto' => $nom_imagen,
'password' => Hash::make($request['password']),
return redirect()->action('HomeController#index'),
]);
}
Laravel 5.5: Execute a method before registration
HomeController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('index');
}
}
You are returning the return value of User::create() which will be a User object which gets converted to json when returned as a response.
Also since your HomeController is protected by 'auth' middleware you need to login the user before redirecting to '/home'
use Illuminate\Support\Facades\Auth;
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => ['required', 'string', 'max:255'],
'nombre' => ['required', 'string', 'max:255','unique:users'],
'telefono' => ['required', 'numeric', 'max:99999999', 'min:00000000'],
'direccion' => ['required', 'string', 'max:255'],
'sueldo' => ['numeric','min:0.01','max:0.99'],
//'foto' => ['string', 'max:255'],
'email' => ['string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:4', 'confirmed'],
]);
if ($request->hasFile('foto')) {
$request = request();
$file = $request->file('foto');
$nom_imagen = time().".".$file->getClientOriginalExtension();
$upload_path = 'imagenes/';
$profile_image_url = $upload_path . $nom_imagen;
$success = $file->move($upload_path, $nom_imagen);
} else {
$nom_imagen = '';
}
$user = User::create([
'name' => $request->input('name'),
'nombre' => $request->input('nombre'),
'telefono' => $request->input('telefono'),
'direccion' => $request->input('direccion'),
'sueldo' => $request->input('sueldo'),
'email' => $request->input('email'),
'foto' => $nom_imagen,
'password' => Hash::make($request['password']),
]);
Auth::guard()->login($user);
return redirect('/home');
}
Move the redirect after create user , try like this
User::create([
'name' => $request->input('name'),
'nombre' =>$request->input('nombre'),
'telefono' => $request->input('telefono'),
'direccion' => $request->input('direccion'),
'sueldo' => $request->input('sueldo'),
'email' => $request->input('email'),
'foto' => $nom_imagen,
'password' => Hash::make($request['password'])
]);
return redirect()->action('HomeController#index'),

Laravel 5.8 register redirect

I'm using Laravel 5.8, still new to PHP and Laravel. When I register, it returns the user in JSON format which is normal from the Register Users.php register function. However, I have a redirectTo() function which should take care of the redirect and redirect the user to some pages a specified, but it's not working. I've tried overriding the redirectPath() function as well which isn't working.
The redirect works perfectly for the login controller.
Any solution or pointers would be appreciated. See RegisterController below.
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Auth;
class RegisterController extends Controller
{
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
//public $redirectTo = '/home';
protected function redirectPath()
{
$role = Auth::user()->role;
if ($role === 'candidate') {
return '/candidate_dashboard';
} elseif ($role === 'employer') {
return '/employer_dashboard';
} elseif ($role === 'contractor') {
return '/contractor_dashboard';
}
}
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
try {
return Validator::make($data, [
'first_name' => ['required', 'string', 'max:255'],
'last_name' => ['required', 'string', 'max:255'],
'role' => ['required', 'string', 'max:50'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
} catch (Illuminate\Database\QueryException $th) {
return back()->withError($th->getMessage())->withInput();
}
}
protected function create(Request $data)
{
try {
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'role' => $data['role'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
} catch (Illuminate\Database\QueryException $th) {
return back()->withError($th->getMessage())->withInput();
}
}
}

Method App\Http\Controllers\Auth\RegisterController::validator does not exist

I am trying to do registration of multi-user in my registration controller and used the following code and checked. But it shows me error:
Method App\Http\Controllers\Auth\RegisterController::validator does not exist.
<?php
namespace App\Http\Controllers\Auth;
use App\Admin;
use App\Manager;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
class RegisterController extends Controller
{
use RegistersUsers;
public function __construct()
{
$this->middleware('guest');
$this->middleware('guest:admin');
$this->middleware('guest:manager');
}
protected function createAdmin(Request $request)
{
$this->validator($request->all())->validate();
$admin = Admin::create([
'name' => $request['name'],
'email' => $request['email'],
'password' => Hash::make($request['password']),
]);
return redirect()->intended('login/admin');
}
protected function createManager(Request $request)
{
$this->validator($request->all())->validate();
$manager = Manager::create([
'name' => $request['name'],
'email' => $request['email'],
'password' => Hash::make($request['password']),
]);
return redirect()->intended('login/manager');
}
}
Try to add validator() function like follow:
protected function validator(array $data, $table)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:'.$table],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
then you can make validation like so:
$this->validator($request->all(), 'table_name')->validate();
change table_name with corresponding name.

laravel testing fails when testing passport oauth2 with virtual database

I'm using virtual test database for my testing. my API is working with postman. but creating problem when writing test. when I execute the test it shows a long list of error containing the following message below-
"message": "Client error: POST http://localhost/oauth/token resulted
in a 401 Unauthorized
response:\n{\"error\":\"invalid_client\",\"message\":\"Client
authentication failed\"}
here is my route-
Route::post('/v1/create', 'API\v1\UserController#register');
here is my controller
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:6', 'confirmed'],
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$http=new Client;
$response=$http->post(url("/oauth/token"),[
'form_params'=>[
'grant_type' =>'password',
'client_id' =>$request->client_id,
'client_secret' =>$request->client_secret,
'password' =>$request->password,
'username' =>$request->email,
'scope' =>''
]
]);
// return response()->json(['success'=>$response], $this->successStatus);
return $response;
}
and here is my test-
<?php
namespace Tests\Feature\API\v1;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use PharIo\Manifest\Email;
class UserTest extends TestCase
{
use WithFaker;
use DatabaseMigrations;
public $mockConsoleOutput = false;
/** #test */
public function a_user_can_create_user(){
$user= factory(User::class)->create(); //create user
$login=$this->actingAs($user,'api'); //user login with api
//create password grant client
$this->artisan('passport:client', ['--password' =>true, '--no-interaction' => true, '--redirect_uri'=>'http://localhost', '--name'=>'test client']);
// fetch client for id and secret
$client = \DB::table('oauth_clients')->where('password_client', 1)->first();
// dd($client->getData());
$email=$this->faker->email();
$password=$this->faker->password;
$newUser=$this->json('POST','/api/v1/create',[
'grant_type' =>'password',
'client_id' => $client->id,
'client_secret' => $client->secret,
'name' => $this->faker->name(),
'email' => $email,
'password' => $password,
'password_confirmation' => $password,
'remember_token' => str_random(10),
]);
// ->assertJsonStructure(['access_token', 'refresh_token']);
dd($newUser);
// $this->assertDatabaseHas('users',['email'=>$email]);
// $newUser->assertJsonFragment(['token_type'=>'Bearer']);
}
}
please help me what am I missing
I've solved it by proxying the request. it was happening because- when I was calling the "oauth/token" endpoint with guzzle- that call was treated as real call and test was not working there. so this helped me a lot to solve the problem.
$tokenRequest = Request::create('oauth/token', 'POST',$request->toArray());
$response = Route::dispatch($tokenRequest);

Laravel: Too few arguments to function 0 passed and exactly 1 expected"

I know this has been asked before. ive seen the questions and answers but cant find something that I can get help from.
I am trying to pass simple data into my database. so far so good.
I believe my problem arises when I try to add the userID since it has to be pulled from Auth. so here is my controller code.
side node , userID is from a foreign table called users. and userID will be used as a foreign key. in the userstable its called "id"
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ShopController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('/shop/addShop');
}
protected function validator(array $data)
{
return Validator::make($data, [
'userid' => ['required', 'string', 'max:255'],
'shopname' => ['required', 'string', 'max:255'],
'address' => ['required', 'string', 'max:255'],
'postal' => ['required', 'string', 'max:255'],
'city' => ['required', 'string', 'max:255'],
'phone' => ['required', 'string', 'max:255'],
]);
}
/**
* Add Users shop after a validation check.
*
* #param array $data
* #return \App\
*/
protected function create(array $data)
{
$userId = Auth::id();
return User::create([
'userid'=> $data[$userId],
'shopname' => $data['shopname'],
'address' => $data['address'],
'postal' => $data['postal'],
'city' => $data['city'],
'phone' => $data['phone'],
]);
}
}
and right here you can see my route.
<?php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::post('/addShop', 'ShopController#create')->name('addShop');
Route::get('/addShop', 'ShopController#index')->name('addShop');
Use Request
Your create function is expecting an array. However, Laravel is passing a POST request. Therefore, use the Request class instead. Your code should read:
namespace App\Http\Controllers;
use User;
use Illuminate\Http\Request;
protected function create(Request $data)
{
$userId = Auth::id();
return User::create([
'userid'=> $data[$userId],
'shopname' => $data['shopname'],
'address' => $data['address'],
'postal' => $data['postal'],
'city' => $data['city'],
'phone' => $data['phone'],
]);
}
I got this error on my project it was because this line of code
Auth::guard()->logoutOtherDevices(); I just comment it and my logout function worked correctly.

Resources