Post method not allowing data in body request Laravel 9 (postman) - php

I've created an api an it works however there is a weird behavior it doesnt allow me to send data in the body of the request.
Here's my code:
api.php
Route::controller(AuthController::class)->group(function () {
Route::post('login', 'login');
Route::post('register', 'register');
Route::post('logout', 'logout');
Route::post('refresh', 'refresh');
Route::get('me', 'me');
});
AuthController.php
class AuthController extends Controller
{
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login','register']]);
}
public function register(Request $request){
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
$token = Auth::login($user);
return response()->json([
'status' => 'success',
'message' => 'User created successfully',
'user' => $user,
'authorisation' => [
'token' => $token,
'type' => 'bearer',
]
]);
}
}
if i send data like this
localhost:8000/api/register?name=odlir4&email=odlirgz4#gmail.com&password=password
it works fine but if i send it like this
this doesn't work, anyone knows why this is happening? i think it should work or am i wrong?
Thank you!

in the route register you define the POST method
api.php
Route::post('register', 'register');
in postman you send data using GET method because it passes parameter
localhost:8000/api/register?name=odlir4&email=odlirgz4#gmail.com&password=password
it should be like this in Tab Body
https://www.postman.com/postman/workspace/published-postman-templates/request/631643-083e46e7-53ea-87b1-8104-f8917ce58a17

You need to get form-data in your controller using below method
public function register(){
$datarequest = $this->input->post();
// other code
}
OR if you want to send request in json
public function register(){
$datarequest = json_decode(file_get_contents('php://input'),true);
// other code
}

Related

Laravel signup method

am trying to do simple function, signup function. Am new in laravel so really does not know why this is not working...
Am getting 419 Page Expired in insomnia.
So this is my method code:
public function signup(Request $request)
{
$data = $request->validate([
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required',
'password' => 'required|min:5|confirmed',
'password_confirmation' => 'required',
];
$registeredUser = User::create($data);
return response()->json($registeredUser);
}
Route:
Route::prefix('api/v1')->group(function () {
Route::group(['namespace' => 'App\Http\Controllers'], function () {
/** signup */
Route::post('/signup', 'AuthController#signup');
});
});
So whats wrong with this code? why am getting 419?

RouteNotFoundException [login] Laravel Sanctum

I am currently learning Laravel and using Sanctum to perform authentication.
I have a route working /register and /login and I am trying to create /me endpoint that's protected using auth:sanctum which as a test just returns the authenticated user.
In my api.php I have the following:
Route::post('/auth/register', [UserController::class, "register"]);
Route::post('/auth/login', [UserController::class, "login"]);
Route::middleware('auth:sanctum')->get('/me', function(){
return auth()->user();
});
In my UserController class I have the following:
class UserController extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function register(Request $request)
{
$user = User::create([
'name' => $request['name'],
'email' => $request['email'],
'password' => bcrypt($request['password'])
]);
return response([
'success' => $user->createToken('API Token')->plainTextToken
]);
}
public function login(Request $request)
{
$attr = $request->validate([
'email' => 'required|string|email|',
'password' => 'required|string|min:6'
]);
if (!Auth::attempt($attr))
{
return response('Credentials not found', 401);
}
return response([
'token' => auth()->user()->createToken('API Token')->plainTextToken
]);
}
public function logout()
{
auth()->user()->tokens()->delete();
return [
'message' => 'Tokens Revoked'
];
}
}
The /login and /register routes work fine, however, when I attempt to use the /logout or /me route which is using auth:sanctum middleware, I get the following error:
Symfony\Component\Routing\Exception\RouteNotFoundException
Route [login] not defined.
Everything I've Google'd seem to show that I've implemented it correctly, so I'm not sure what I'm missing.
I managed to figure out the problem with some help from #LessMore.
I think most of the problem the auth.php being wrong. Under config/auth.php, under the api section change the driver from token to session, so it should be as follows:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'session',
'provider' => 'users',
'hash' => false,
],
],
The other thing was I was forgetting to add the Authorization header with the bearer token that is returned on the login and to put Accept application/json header.

Where am I going wrong when creating authentication in Laravel?

PHP 7.4
Laravel 8
Route 1 (super.com/auth):
Receives email, password data and makes authentication.
$result = Auth::Attempt(['password' => 'superpwd', 'email' => 'super#mail.ru'], true);
Auth::check() // true
Route 2 (super.com/testAuthCheck):
We check the authentication.
Auth::check(); // false
It turns out that the authentication is not saved in the session.
Please tell me where I'm wrong? May be session or some setting, or modules...
Full code:
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Hash;
class AuthUser extends Controller
{
public function register(Request $request)
{
$request->validate([
'name' => 'required|string',
'lastname' => 'required|string',
'secondname' => 'required|string',
'tel' => 'required|numeric',
'password' => 'required|string',
]);
$user = User::create([
'name' => $request->name,
'lastname' => $request->lastname,
'secondname' => $request->secondname,
'tel' => $request->tel,
'password' => Hash::make($request->password),
'email' => '',
]);
$login = Auth::login($user);
return response()->json([
'message' => 'Success!',
'login' => $login
]);
}
public function test(Request $request) {
if(Auth::Attempt(['password' => 111, 'email' => 'a#b.ru'], true)) {
$request->session()->regenerate();
$result = Auth::check();
dump($result); // true
}
}
public function test2(Request $request) {
$result = Auth::check();
dump($result); // false
}
Using dump will most likely cause more problems while debugging this.
public function test(Request $request) {
if(Auth::Attempt(['password' => 111, 'email' => 'a#b.ru'], true)) {
$request->session()->regenerate();
$result = Auth::check();
//dump($result); ***will terminate the request and the session will not be set correctly ***
info($result); // check storage/logs/laravel.log
}
}

Laravel routing not completing

I am somewhat new to Laravel.
I have created a form, submitted it for authorisation but then I am told (by Firefox) the routing will never complete. I know the login has worked as I intercepted it.
Here is my routes.php:
Route::get('/',function()
{
return view('welcome');
})->name('home');
Route::get('/welcome', function () {
return view('welcome');
});
Route::post('/signin',
[
'uses' =>'UserController#postSignIn',
'as' => 'SignIn'
]);
Route::get('/dashboard',
[
'uses' => 'UserController#getDashboard',
'as' => 'DashBoard',
'middleware' => 'auth'
]);
Route::get('/logout',
[
'uses' => 'UserController#getLogout',
'as' => 'Logout'
]);
and here is the UserController:
class UserController extends Controller
{
public function postSignIn(Request $request)
{
$this->validate($request,
[
'email' => 'required | email',
'password' => 'required'
]);
if (Auth::attempt([ 'email' => $request['email'], 'password' =>$request['password'] ]) )
{
//exit("authorised");
$message = "you are now logged in";
return redirect()->route('DashBoard')->with(['successmessage' =>$message]);
}
else
{
$message = "username\password combination not correct";
//exit('not - email = '.$request['email'].' password = '. $request['password']);
return redirect()->back()->with(['errormessage' => $message] );
}
}
public function getLogout()
{
Auth::logout();
return redirect()->route('home');
}
public function getDashboard()
{
return redirect()->route('DashBoard');
}
}
As can be seen by what is commented out the authorisation is OK
But I get this from Firefox
The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
Just use to() in your return as
return redirect()->to('DashBoard')->with(['successmessage' =>$message]);
add this to your route
Route::get('/signin',
[
'uses' =>'UserController#postSignIn',
'as' => 'SignIn'
]);

MethodNotAllowedHttpException in RouteCollection.php line 219 error laravel:

I get this error when i try to access the post signin route. I'm new to laravel and i can't seem to figure out how to solve this error. Please help.
My Routes.php
Route::group(['middleware' => ['web']], function () {
Route::get('/', [
'uses'=>'\ocsaf\Http\Controllers\HomeController#index',
'as'=>'home',
]);
/*
*Authentication
*/
Route::get('/signup', [
'uses'=>'\ocsaf\Http\Controllers\AuthController#getSignUp',
'as'=>'auth.signup',
'middleware' => ['guest'],
]);
Route::post('/signup', [
'uses'=>'\ocsaf\Http\Controllers\AuthController#postSignUp',
'middleware' => ['guest'],
]);
Route::get('/signin', [
'uses'=>'\ocsaf\Http\Controllers\AuthController#getSignIn',
'as'=>'auth.signin',
'middleware' => ['guest'],
]);
Route::post('/signup', [
'uses'=>'\ocsaf\Http\Controllers\AuthController#postSignIn',
'middleware' => ['guest'],
]);
Route::get('/signout', [
'uses'=>'\ocsaf\Http\Controllers\AuthController#getSignOut',
'as'=>'auth.signout',
]);
/*
*search
*/
Route::get('/search', [
'uses'=>'\ocsaf\Http\Controllers\SearchController#getResults',
'as'=>'search.results',
]);
/*
*Profile
*/
Route::get('/user/{username}', [
'uses'=>'\ocsaf\Http\Controllers\ProfileController#getProfile',
'as'=>'profile.index',
]);
Route::get('/profile/edit', [
'uses'=>'\ocsaf\Http\Controllers\ProfileController#getEdit',
'as'=>'profile.edit',
'middleware'=>['auth'],
]);
Route::post('/profile/edit', [
'uses'=>'\ocsaf\Http\Controllers\ProfileController#postEdit',
'as'=>'profile.edit',
'middleware'=>['auth'],
]);
Route::post('/profile/edit', [
'uses'=>'\ocsaf\Http\Controllers\StatusController#postStatus',
'as'=>'status.post',
'middleware'=>['auth'],
]);
});
AuthController.php
namespace ocsaf\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use ocsaf\Models\User;
class AuthController extends Controller
{
public function getSignUp()
{
return view('auth.signup');
}
public function postSignUp(Request $request)
{
$this->validate($request, [
'email' => 'required|unique:users|email|max:255',
'username' => 'required|unique:users|alpha_dash|max:255',
'password' => 'required|min:6',
]);
User::create([
'email' => $request-> input('email'),
'username' => $request-> input('username'),
'password' => bcrypt($request -> input('password')),
]);
return redirect()
->route('home')
->with('info', 'You have signed up, Please sign in!');
}
public function getSignIn()
{
return view('auth.signin');
}
public function postSignIn(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
if(!Auth::attempt($request -> only(['email', 'password' ]),
$request -> has('remember'))){
return redirect() ->back()->
with('info', 'could not sign you in with those details ');
}
return redirect() ->route('home')->with('info', 'You are now signed in');
}
}
my signin.blade.php form statement
<form class="form-vertical" role = "form"
method = "post" action = "{{ route('auth.signin'); }}">
Your form method is post but for the route auth.signin the HTTP verb is get.

Categories