Laravel post request route - laravel

enter image description hereI have a following Controller in php laravel:
// .....
class RegisterController extends Controller
{
//...
//...
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
I use the following route:
Route::post('api/auth/register', 'Auth\RegisterController#create');
I am getting the following error: "Too few arguments to function App\Http\Controllers\Auth\RegisterController::create(), 0 passed and exactly 1 expected"
I need your help to pass Request parameters to my function (Form route properly)

Try changing your method parameter to Request $request
to obtain an instance of the current HTTP request via dependency
injection, you should type-hint the Illuminate\Http\Request class on
your controller method. The incoming request instance will
automatically be injected by the service container
and get the data from the request fields:
protected function create(Illuminate\Http\Request $request)
{
return User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
}
If you do not want to write all the Request namespace in the method parameter, add on the top of the file:
use Illuminate\Http\Request;
then, just use the name of the class:
protected function create(Request $request)
{
//...
}

You can do it in this way,
use Illuminate\Http\Request;
class RegisterController extends Controller
{
protected function create(Request $request)
{
$data = $request->all();
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}

Related

Assigning the role while user registration Laravel

I'm trying to make a register page with role as a radio button(consumer, supplier, Admin)
but it show me this error when I test the query in postman
Error: Class "App\Http\Models\Role" not found in file
my controller:
public function register(Request $request)
{
$request->validate([
'first_name'=>'required|string',
'last_name'=>'required|string',
'email'=>'required|string|unique:users',
'password'=>'required|string|min:6',
'phone_number'=>'required|string|min:10',
'role_name'=>'required|string'
]);
$role_a = $request->role_name;
if ($role_a == 'صاحب متجر'){
$role=Role::select('role_id')->where('role_name','صاحب متجر')->first();
$user->roles()->attach($role);
return response()->json($user);
}
elseif ($role_a == 'مشتري'){
$role=Role::select('role_id')->where('role_name','مشتري')->first();
$user->roles()->attach($role);
return response()->json($user);
}
$user=User::create([
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'email' => $request->email,
'password' => Hash::make($request->password),
'phone_number' => $request->phone_number,
]);
And my use statement:
use Illuminate\Http\Request;
use App\Http\Models\User;
use App\Http\Models\Role;
use Illuminate\Support\Facades\Hash;
And my route:
Route::post('/register','App\Http\Controllers\AuthController#register');
and this what I have in tables:
Note: I didn't use custom packages like spatie for example
Thank you for trying to help!
You miss adding the Request class as an argument into your method. Your method should look like this:
public function register(Request $request)
{
//after validation
$data = $request->validated();
}
Dont forget to add use Illuminate\Http\Request; in your use statement.

Laravel resources when called in usersController gives me a different path and an error

I am a week old into laravel and am working on my first api.
Everything worked well till I decided to introduce resources. When I call the UserResource method I get an error that I can't understand. I have googled but haven't found an answer yet.
This is the error I get when I run on postman
Symfony\Component\Debug\Exception\FatalThrowableError: Call to undefined function App\Http\Controllers\Api\UserResource()
The Resource file is in app/Http/Resources/
Checkout the path returned
App\Http\Controllers\Api\UserResource
yet the one I add is
App\Http\Resources\UserResource;
Laravel Code:
app/Http/Controllers/Api/usersController.php
use App\User;
use App\Http\Resources\UserResource;
class UsersController extends Controller
{
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
$email = $request->email;
$password = $request->password;
$user = User::where('email', $email)->where('password', $password)->first();
if($user) {
$success['token'] = $user->createToken('myapp')-> accessToken;
$success['user'] = UserResource($user);
return response()->json(['success' => $success], 200);
}
return response()->json(['error' => 'UnAuthorised'], 401);
}
}
app/Http/Resources/UserResource.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'first_name' => $this->first_name,
'other_names' => $this->other_names,
'email' => $this->email,
'phone_number' => $this->phone_number,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
You forgot the new operator trying to instantiate the UserResource class. Without the new operator, PHP will look for a function called UserResource in the current namespace, therefore you get that error.

Laravel 5.5 Api Registration issue

I have been trying to get this api up and running and keep on experiencing this error when I test in Postman.
1. api.php
Route::group(['middleware' => ['api','cors']], function () {
Route::post('auth/register', 'Auth\RegisterController#create');
});
2. RegisterController
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}}
Postman configuration set to Post, the body is set to raw and JSON(application/json) Below is the postman json code.
{
"name": "Walter White",
"email": "wwhite#someemaildomain.net",
"password": "testpassword"
}
Below is the error
Too few arguments to function App\Http\Controllers\Auth\RegisterController::create(), 0 passed and exactly 1 expected in file C:\xampp\examplestuff
In order to fix your registration you should change your route definition to:
Route::group(['middleware' => ['api','cors']], function () {
Route::post('auth/register', 'Auth\RegisterController#register');
});
I assume your RegisterController is using the trait RegistersUsers. This trait is providing the register method, which is using the RegisterController::create method to create the new user itself.
Pass Request to your create function like:
protected function create(Request $request){...
and access your data like this:
$request->name
you have to do validation also plz check below answer
protected function create(Request $request)
{
$data = $request->json()->all();
$validator = Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
if ($validator->fails()) {
foreach ($validator->messages()->getMessages() as $field_name => $message){
$messages[] = $message[0];
}
$messages = $messages;
$message = implode(',',$messages);
$response = $messages;
return $response;
}else{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}

Laravel: Undefined variable: request

I don´t can find the problem. Where ist it? "Undefined variable: request"
public function login()
{
// Validate the form data
$this->validate($request, [
'email' => 'required|email',
'passwort' => 'required|min:6'
]);
// Attempt to log the user in
if (Auth::guard('admin')->attempt(['email' => $request->email, 'passwort' => $request->passwort], $remember)) {
// if successful, then redirect to their intended location
return redirect()->intended(roue('admin.dashboard'));
}
// if unsuccessful, then redirect back to the login with the form data
return redirect()->back()->withInput($request->only('email', 'remember'));
}
You need to inject Request object:
public function login(Request $request)
Also, add this line to the top of your class:
use Illuminate\Http\Request;
Alternatively, you can just use request() instead of $request in your code.
You have not defined the 'request' variable but you are using it in your code.
Edited Code
public function login(Request $request)
{
// Validate the form data
$this->validate($request, [
'email' => 'required|email',
'passwort' => 'required|min:6'
]);
// Attempt to log the user in
if (Auth::guard('admin')->attempt(['email' => $request->email, 'passwort' => $request->passwort], $remember)) {
// if successful, then redirect to their intended location
return redirect()->intended(roue('admin.dashboard'));
}
// if unsuccessful, then redirect back to the login with the form data
return redirect()->back()->withInput($request->only('email', 'remember'));
}
Also, add this line to the top of your class:
use Illuminate\Http\Request;

Call to undefined method Illuminate\Http\JsonResponse::validate() in Laravel 5.3

I am implementing a registration form using JSON post request and laravel 5.3 with the below Controller settings
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
use RegistersUsers;
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
$data = $data['Register'];
$validator = Validator::make($data, [
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
if($validator->fails())
{
$errors = $validator->errors()->all()[0];
//dd($errors);
return response()->json(['errors'=>$errors]);
}
else
{
return $validator;
}
}
protected function create(array $data)
{
$data = $data['Register'];
//dd($data);
User::create([
//'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
return response()->json(['success' => $data['email']], 200);
}
}
But i want to track server errors in the event of multiple registration with the same email. I have handled this on the client side but in need to handle on the backend too.
The Problem is with the validator function it keep returning below error
FatalThrowableError in RegistersUsers.php line 31:
Call to undefined method Illuminate\Http\JsonResponse::validate()
I have checked inside the framework code and there is a validate method which seems to be unrecognized with the json response any ideas?

Resources