Laravel responding with html default page ignoring controller - php

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',
]);

Related

How to stop auto login after registration in Laravel 8 breeze

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.

Laravel - Can't redirect after sending mail

After sending a Mail (which my code does), I want to redirect the user to another view (main.blade.php) but nothing is happening.
In my form, I call the sendemail route, here is the code:
<form method="POST" action="{{ route('sendemail') }}">
In my web.php the routes are defined as following:
Route::get('/', 'PagesController#main')->name('main');
Route::post('/sendemail', "SendEmailController#send")->name('sendemail');
And my SendEmailController.php looks like:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\SendMail;
use Illuminate\Support\Facades\Redirect;
class SendEmailController extends Controller
{
public function send()
{
$data = request()->validate([
'name' => 'required',
'email' => 'required|email',
'message' => 'required',
'company' => 'required',
'knowledge' => 'required',
'reason' => 'required',
'subject' => 'required'
]);
Mail::to('example#example.eu')->send(new SendMail($data));
return redirect()->to('main');
}
}
Have read this topic : Redirect to contacts page after submitting form in laravel 4
But didn't work for me.
EDIT:
The problem did not came from Laravel but from AJAX, problem solved.
to method accepts path, not route name. It will work with
return redirect()->to('/');
To use route name in redirection you have to use
return redirect()->route('login');
Docs.

Laravel API: The POST method is not supported for this route. Supported methods: GET, HEAD

I am sending a post request to http://localhost/projects/webdevlist/public/api/register and getting the 405 error:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The POST method is not supported for this route. Supported methods: GET, HEAD.
routes\api.php:
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('/register', 'Api\AuthController#register');
Api\AuthController.php:
<?php
namespace App\Http\Controllers\Api;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|max:55',
'email' => 'required|email',
'password' => 'required|confirmed'
]);
$user = User::create($validatedData);
$accessToken = $user->createToken('token')->accessToken;
return response(['user' => $user, 'access_token' => $accessToken]);
}
}
If I remove the form validation then I can do post requests just fine and return a result in postman like this.
<?php
namespace App\Http\Controllers\Api;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function register(Request $request)
{
return response()->json([
$request->name,
$request->email,
$request->password,
]);
}
}
But something is wrong with my validation. Why does the validation cause me to no longer be able to accept POST requests?
Here is my POST request:
The problem with your validation is the password field.
Your rule say that it need to be required and confirmed, but confirmed against which field?
You need to add a field with name password_confirmation your view, if not added yet.
<input type="password" name="password_confirmation" />
And then add a new rule for password_confirmation field:
$validatedData = $request->validate([
'name' => 'required|max:55',
'email' => 'required|email',
'password' => 'required|confirmed',
'password_confirmation' => 'required'
]);

POST calls return 404 In Laravel

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;

Auth::attempt() always returns false for default brand new installation

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')),

Categories