Receive empty Array as output when request is sent - laravel

I created 2 classes called UserStoreRequest and UserAuthController in my laravel project. UserStoreRequest is a FormRequest to Validate the Request coming from the user. Once I send parameters, I just want to access these inside the Register method, but I get an empty array as response, instead of parameters sent.
UserAuthController:
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\UserStoreRequest;
use App\Models\User;
class UserAuthController extends Controller
{
public function register(UserStoreRequest $request)
{
dd($request->all());
/* $data = $request->validate([
'name' => 'required|max:255',
'email' => 'required|email|unique:users',
'password' => 'required|confirmed'
]);
$data['password'] = bcrypt($request->password);
$user = User::create($data);
$token = $user->createToken('API Token')->accessToken;
return response(['user' => $user, 'token' => $token]);*/
}
}
UserStoreRequest:
namespace App\Http\Requests;
use Illuminate\Http\Request;
class UserStoreRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
//
];
}
}
Below I put the route used in the API class to send parameters:
Route::post('/register', 'App\Http\Controllers\Auth\UserAuthController#register');

It looks like you're trying to use a Form Request. To do so, make sure you extend the proper parent class.
// Incorrect
use Illuminate\Http\Request;
class UserStoreRequest extends Request { /* ... */ }
// Correct
use Illuminate\Foundation\Http\FormRequest;
class UserStoreRequest extends FormRequest { /* ... */ }
The Laravel dependency injection container is able to instantiate a new instance of your existing Request, which is why you don't receive any errors and an instance of your request is available to the controller. However, Laravel doesn't know to populate it with the actual request data. That's where FormRequest comes in.

Related

How to add errors after FormRequests validation?

How to add errors after FormRequests validation?
password_repository->update() will return an error if the current passwords entered do not match.
password_repository->update() calls an external API.
I want to add an error in the controller depending on the return value of the repository.
In PasswordRequest, validation after calling the external API cannot be described, so I am in trouble.
For this reason I want to add an error in the controller after doing password_repository->update().
PasswordController.php
public function completeEdit(PasswordRequest $request)
{
$input = $request->only(['password', 'new_password']);
$data = $this->password_repository->update($input);
//I want to add an error at this point!!!
return view('pages.password.edit.complete');
}
}
PasswordRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class PasswordRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'password' => 'required',
'new_password' => 'required|confirmed',
'new_password_confirmation' => 'required',
];
}
}
Redirect with errors could help you.
return redirect()->back()->withErrors([
'Password not correct',
]);
Or return to a specific route.
return redirect()->route('password.create')->withErrors([
'Password not correct',
]);

Url for API to login and get access token

I want to validate the email and password of someone connecting through an API.
The idea is that they login through POST to site.com/api/v1/token?email=foo#bar.com&password=foobar
I was reading that best practices should be to make a https://laravel.com/docs/7.x/validation#creating-form-requests to handle the validation, but I couldn't understand how to validate the $user, because when I created the new Class there wasn't any request there.
I'm not sure if I'm missing something.
I was able to do it through the Controller just checking if the user exists and the password is valid.
The app would ping this URL with email/password, then get a Token as a response with the $user information and use this token to post/edit/delete other data
First you have to create a FormRequest class by using artisan command:
php artisan make:request ApiLoginRequest
After artisan command, it will create a new file inside you app/Http/Request with name ApiLoginRequest.php.
Inside this file you have to define validation rules like this.
<?php
namespace App\Http\Request;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Request;
class ApiLoginRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules(Request $request)
{
$rules = [
'email' => 'required|email|exists:users,email',
'password' => 'required'
];
return $rules;
}
/**
* #name messages
*
* #description
*/
public function messages() {
return [
'email.required' => 'Required',
'password.required' => 'Required',
'email.email' => 'Must be a valid email address',
'email.exists' => 'Email address not found'
];
}
}
Then after you have to use this Request class inside your controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Request\ApiLoginRequest;
class ApiLoginController extends Controller {
public function login ( ApiLoginRequest $request ){
$user = \App\User::where('email', $request->get('email'))->find();
if( \Hash::check( $user>password, $request->password ) ){
// Do Login processed
}else{
$data = [
'success' => false,
'message' => 'Password dows not match'
];
return response()->json( $data, 500);
}
}
}
Like this you can use FormRequest class and benefit of this FormRequest class you can reuse this validation rules and also your controller looks good.

Laravel :Too few arguments to function App\Http\Controllers\Auth\LoginController::authenticated(), 2 passed

I am getting this error On GeoIP::getLocation when I send data to MySQL Database
This Error:
"Too few arguments to function App\Http\Controllers\Auth\LoginController::authenticated(), 2 passed in C:\xampp\htdocs\codecrowne\vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php on line 108 and exactly 3 expected"
I am getting above error on this code on auth logincontroller .
This Is My Auth LoginController.php On User Login i am updating user data into database. All the data store into database but when i add this code 'current_location' => GeoIP::getLocation('2405:204:970a:d9b3:10a3:5280:9064:3f31'), i am getting this error
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Jenssegers\Agent\Agent;
use Carbon\Carbon;
use App\User;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Closure;
use GeoIP;
use Location;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
function authenticated(Request $request, $user, Closure $next)
{
// Chrome, IE, Safari, Firefox, ...
$agent = new Agent();
$browser = $agent->browser();
// Ubuntu, Windows, OS X, ...
$platform = $agent->platform();
$user->update([
'last_signin' => Carbon::now()->toDateTimeString(),
'ip_address' => $request->getClientIp(),
'browser_login' => $agent->browser(),
'browser_version' => $agent->version($browser),
'device_login' => $agent->platform(),
'device_version' => $agent->version($platform),
'current_location' => GeoIP::getLocation('2405:204:970a:d9b3:10a3:5280:9064:3f31'),
'language' => $agent->languages(),
'root' => $agent->robot(),
'https' => $request->server('HTTP_USER_AGENT'),
]);
}
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest',['except'=>['logout', 'userLogout', 'profile']]);
}
public function userLogout()
{
Auth::guard('web')->logout();
return redirect('/');
}
}
Route File:
//User Auth Route Function
Auth::routes();
The AuthenticatesUsers trait you are including into this class contains an authenticated method which you are overriding with a different method signature containing an additional parameter.
This method signature only expects 2 arguments, as you can see:
protected mixed authenticated(Request $request, mixed $user)
However, in your controller, you have a third parameter Closure $next. The error message is correctly advising you that the method is expecting 3 parameters, however, it's only being provided with 2.
If you remove the third parameter (you're not using it anyway), your code should work.

How to Use custom request (make:request)? (laravel) Method App\Http\Requests\Custom::doesExistI does not exist

I created a custom request to make my own validation. As i follow these article.
I created ProfileRequest
php artisan make:request ProfileRequest
Inside my ProfileRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ProfileRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|min:10',
'age' => 'required|numeric'
];
}
}
My problem is when I use the ProfileRequest inside the controller, like below:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
public function update(ProfileRequest $request){
return "123";
}
}
It returns an error like these below:
Class App\Http\Controllers\ProfileRequest does not exist
I need your help Sirs. Somebody know how to use the custom request?
In ProfileRequest change extends FormRequest to extends Request. Then add use Illuminate\Http\Request; above the class. Code should look like below.
<?php
namespace App\Http\Requests;
use Illuminate\Http\Request;
class ProfileRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|min:10',
'age' => 'required|numeric'
];
}
}
Then put App\Http\Requests\ProfileRequest; in your controller.
create ProfileRequest
php artisan make:request Profile/ProfileRequest
inside ProfileRequest
<?php
namespace App\Http\Requests\Profile;
use Illuminate\Foundation\Http\FormRequest;
class ProfileUpdate extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|min:10',
'age' => 'required|numeric'
];
}
}
Then put use App\Http\Requests\Profile\ProfileRequest in the controller.
You have imported use Illuminate\Http\Request;
You have to import ProfileRequest instead of Request on your controller,
just this:
use App\Http\Requests\ProfileRequest;
Try with this,
First of all You have to import request in your controller,
use App\Http\Requests\ProfileRequest;
$validated = $request->validated();
if ($validated) {
// ...
}
Hope this helps :)
You need to import App\Http\Requests\ProfileRequest in your controller
like: use App\Http\Requests\ProfileRequest
then try: composer dumpautoload, php artisan cache:clear
In your ProfileRequest.php
change
use Illuminate\Foundation\Http\FormRequest;
to
use Illuminate\Http\FormRequest;
And then just
php artisan config:cache
composer dumpautoload

Default controller in Route::group for routing purposes?

I want to show some user data by id. Simple.
user/{id} -> get data from a Controller's method.
I have this:
Route::group(['prefix' => 'user/{id}', 'where' => ['id' => '[0-9]+']], function() {
Route::get('delete', 'UserController#delete')->name('admin.access.user.delete-permanently');
Route::get('restore', 'UserController#restore')->name('admin.access.user.restore');
Route::get('mark/{status}', 'UserController#mark')->name('admin.access.user.mark')->where(['status' => '[0,1]']);
Route::get('password/change', 'UserController#changePassword')->name('admin.access.user.change-password');
Route::post('password/change', 'UserController#updatePassword')->name('admin.access.user.change-password');
});
How can I access a method as a default for user/{id}?
You can do this in your controller
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* Show the profile for the given user.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//Fetch and send the user to the "profile" blade file in the folder "resources/views/user"
return view('user.profile', ['user' => User::findOrFail($id)]);
}
public function changePassword($id)
{
$user = User::findOrFail($id);
return $user->update(
'password' => bcrypt(123456)
);
}
}

Resources