I am creating signup Api 1st call is GET and 2nd is POST call.
When I make GET[POSTMAN] call I get proper response from the controller but when I make POST it returns 404.
web.php
// sign up api
Route::get('signup','Api\RegistrationController#createUser');
Route::post('/signup','Api\RegistrationController#storeUser');
RegistrationController.php
public function createUser(){
return "Get : Sign up";
}
public function storeUser() {
// validate the form
$this->validate(request(),[
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required',
'password' => 'required'
]);
// create and save the user
$user = Register::create(request(['firstname', 'lastename', 'email', 'password']));
return "Registration complete";
}
I am using laravel 5.4. When route url is kept same (i.e signup) then GET method executes for POST call, when route url different it returns 404.
Screenshot : its a POST call but GET route executed
Try this and let me know:
use Illuminate\Http\Request;
public function storeUser(Request $request) {
// validate the form
$this->validate($request,[
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required',
'password' => 'required'
]);
// create and save the user
$user = Register::create($request->all());
return "Registration complete";
}
Note: When developing api's always define Api routes in api.php file.
Write All your API Routes in api.php file instead of web.php
use Illuminate\Http\Request;
public function storeUser(Request $request) {
// first check whether your request is coming here or not
// if not coming
// it is the issue of Routing
dd('coming..');
//if it prints coming then comment this dd
$this->validate($request,[
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required',
'password' => 'required'
]);
$user = Register::create($request->all());
}
For api requests , you should not use a custom Http Request that Extends FormRequest but instead
use Illuminate\Http\Request;
Related
I'm trying to make a custom Auth controller with this code:
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function register(Request $request)
{
//validate the request
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8|confirmed',
]);
$data = $request->all();
//create new user
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
//return response
return response()->json(['message' => 'Successfully created user!'], 201);
}
}
the controller should create a new User entry inside the database, the User Model is Laravel's default one, no change has been made.
In my api.php routes file I have this simple routes setup:
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('/register', [AuthController::class, 'register']);
the problem is that when I try to send a POST request to /api/register Laravel responds with the default html page:
what am I doing wrong here? Consider that this should be only the back-end of my app so I don't need to setup any view
In your register method you have validation. If validation fails, it returns you back with validation errors. So you have an error in your $request fields somewhere.
Name should be string, email must be a valid email and should be unique, meaning that none of the existing users should have it. For password you must have confirmation, and that's where i think the problem is.
You should pass to this GET API route not only 'name', 'email' and 'password', but also 'password_confirmation' field which contains same password as 'password' field. I suggest for you to remove this rule to simplify the request, like this :
//validate the request
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
]);
Hi I am fairly new to Laravel framework. I am trying to create a separate controller replicating the registeredusercontroller.php in laravel breeze to have a function for admin user to be able to add new users. But I am having trouble with auto login and as soon as I add a new user it automatically logs in to the new user. How can I stop this from happening. I saw posts stating to remove
$this->guard()->login($user);
but when I see the app/Auth/registeredusercontroller.php I don't see that line.
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|confirmed|min:8',
]);
Auth::login($user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]));
$user->attachRole('user');
event(new Registered($user));
return redirect(RouteServiceProvider::HOME);
}
how can I stop the auto login after registration.
Any help is greatly appreciated.
You can do this proper way like using custom request handler.
The parameter you need is name, email, password.
So add CreateUserRequest above app/http/request
<?php
namespace App\Http\Requests;
use Illuminate\Http\Request;
class CreateUserRequest extends Request
{
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|confirmed|min:8',
];
}
}
And into your controller just do this;
public function store(CreateUserRequest $request) // add your custom request as a parameter
$user = User::create($request)
These codes makes your code structure clear and clean.
Im trying to do a Put/Patch Request, I am using Postman, this is my current Code:
class CustomerController extends Controller
{
public function getAllCustomer()
{
return Customer::get();
}
public function addNewCustomer(Request $request)
{
$validatedData = $request->validate([
'Title' => 'required',
'Name' => 'required|max:255',
'Surname' => 'required|max:255',
'Email' => 'required',
'Phone' => 'required',
'Password' => 'required',
'dateofBirth' => 'required'
]);
return \app\model\Customer::create($request->all());
}
public function update (Request $request , Customer $id)
{
$id->update($request->all());
}
And this my route:
Route::put('Customer/{id}' , 'CustomerController#update');
Im trying to insert some Parameters into Postman, but I think the way I do it is not correct, right now I do it like this:
Im not getting any Errors, but nothing is happening, maybe somebody knows a solution.
I want to Change the Name of the customer.
Thanks!
Try to set x-www-form-urlencoded for body in postman.
I tried lot to search about the problem. I couldn't find any solution. Please help me to understand what i am doing wrong.
I am attaching the code:
UserController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
public function signup(Request $request){
$this->validate($request,[
'name' => 'required',
'email' => 'required|unique:users',
'password' => 'required'
]);
$user = new User([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => bcrypt($request->input('password ')),
]);
$user->save();
return response()->json([
'state' => 'success',
'message' => 'User created.'
],201);
}
public function signin(Request $request){
$credentials = $request->only('email', 'password');
dd(Auth::attempt($credentials));
if (!$token = $this->guard()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
}
And i have routes in api.php
Route::prefix('user')->group(function () {
Route::post('signup', 'UserController#signup');
Route::post('signin', 'UserController#signin');
});
I have
I have this in database
I sent the below json to signup first, but then when i sent to signin i am getting failed.
{
"name":"ironman",
"email":"ironman#yahoo.com",
"password":"avengers"
}
This is a brand new installation of laravel 5.4 (same with 5.5), Using detailt User migration and model came with it.
When i tried to diagnose the problem myself, i found that the password_very is returning false all the time in Auth package.
I am using default password field, hashing it while creating users as other similar questions answered.
I am using php artisan serv.
I am using postman to send this request.
Please help,
This is pulling null from the request:
$request->input('password '); // notice the space
'password' => bcrypt($request->input('password ')),
You probably did not intend to put a space at the end of the input name:
$request->input('password'); // no space
'password' => bcrypt($request->input('password')),
Laravel 5.5
public function register(Request $request) {
request()->validate([
'email' => 'required:email'
'password' => 'required|min:6'
]);
return response()->json(["message" => "Hello World"]);
}
If validator is fails, not giving error messages. Redirecting main page.
If the code you're using redirects you to the previous page when validation fails, it means that you didn't tell the server what kind of response you want to receive.
Set a proper header to get JSON. It will make the validator send JSON in response. For example:
$.ajax({
headers: {
Accept : "application/json"
},
...
});
Then this code will work as expected:
public function register(Request $request)
{
$request->validate([
'email' => 'required:email'
'password' => 'required|min:6'
]);
return response()->json(["message" => "Hello World"]);
}
I had the same problem when testing my rest api in Postman application.
if we don't want to modify our current code of laravel redirect repose, we have to put Accept:-application/json and ContentType:-application/json
For modifying code in controller class file, i did it like this and got the json response instead of redirecting to home page.
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',
]);
if ($validator->fails()) {
return response()->json($validator->errors());
} else {
// do something
}
}
before it looks like below codes it was redirecting to home page
This is validator function
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
]);
}
public function register(Request $request)
{
// Here the request is validated. The validator method is located
// inside the RegisterController, and makes sure the name, email
// password and password_confirmation fields are required.
$this->validator($request->all())->validate();
// A Registered event is created and will trigger any relevant
// observers, such as sending a confirmation email or any
// code that needs to be run as soon as the user is created.
event(new Registered($user = $this->create($request->all())));
// After the user is created, he's logged in.
$this->guard()->login($user);
// And finally this is the hook that we want. If there is no
// registered() method or it returns null, redirect him to
// some other URL. In our case, we just need to implement
// that method to return the correct response.
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
You can do this like this :
$validator = Validator::make($request->all(), [
'email' => 'required|email', //use pipe here to apply multiple validations rules and add a ','
'password' => 'required|min:6'
]);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()]);
}
return response()->json(["message" => "Hello World"]);
The validation is working well, but, $request->validate() will redirect you to the previous page. I recommend you to manually create your validations:
Manually Creating Validations.
You could do something like this:
use Illuminate\Http\Request;
use Validator;
class YourClass extends Controller{
public function yourFunction(Request $request) {
$validator = Validator::make($request->all(),[
'field_1' => 'rule1|rule2',
'field_2' => 'rule1|rule2'
]);
if ($validator->fails()) {
return response()->json($validator->errors());
} else {
/*Something else*/
}
}
}
try this, hope this code can help you
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);