Parameter is not passing to controller in Laravel - laravel

Let's take an example.
https://www.example.net/xyz?page=2
Route File
Route::get('/xyz', 'controller#getpages');
Controller
public function getpages(Request $request) {
dd($request->all());
}
Showing result as
array:1 [▼
"/xyz" => null
]
instead of
array:1 [▼
"page" => "2"
]

try:
public function getpages(Request $request) {
print_r($request->page);
}
Also make sure you use : use Illuminate\Http\Request;

try
$query = $request->query();
$page = $request->query('page');
In your code there is a mistake. you missed $ symbol
public function getpages(Request $request) {
dd($request->all());
}

use Illuminate\Http\Request;
use App\Http\Requests;
public function getpages(Request $request) {
$request = $request->only('page');
dd($request);
}
There is no array. just only one parameter "$page"

Try below code:
This is user register controller:
use Illuminate\Http\Request;
use App\User;
public function register(Request $request){
$data = $this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required'
]);
$data['password'] = app('hash')->make($data['password']);
User::create($data);
$credentials = $request->only('email', 'password');
if ($token = $this->guard()->attempt($credentials)) {
return $this->respondWithToken($token);
}
return response()->json(['error' => 'Unauthorized'], 401);
}

The Problem was in .htaccess file, so i retrieve the old .htaccess and putted it.

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 Auth::attempt ans Hash::check not working

I try make rest API with Laravel 8 + Sanctum. And my database is MySql Maria DB.
I create LoginController and make function call login. When i try my API, it's always return Unauthorized. I pretty sure my USERNAME and PASSWORD is correct.
This is my LoginController
public function store(Request $request) {
$user = User::create(
[
"USERNAME" => $request->username,
"PASSWORD" => Hash::make($request->password),
"ADM_MST_SITE_ID" => 0,
]
);
$token = $user->createToken('apiToken')->plainTextToken;
$res = [
'user' => $user,
'token' => $token
];
return response($res, 201);
}
public function login(Request $request)
{
$data = $request->validate([
'username' => 'required|string',
'password' => 'required|string'
]);
$user = User::where('username', $data['username'])->first();
$credentials = request(['username', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$token = $user->createToken('apiToken')->plainTextToken;
$res = [
'user' => $user,
'token' => $token
];
return response($res, 201);
}
Model
////
protected $table = 'adm_mst_user';
protected $guarded = ['ID'];
public function getAuthPassword()
{
return $this->PASSWORD;
}
////
The store function is work well, the new data are inserted to my database. But, when i login with username and password, it's not working.
I try 2 different auth check, using Auth::attempt and Hash::check.
I don't know where the error coming from. It's always return Unauthorized.
$user = User::where('username', $data['username'])->first();
$this->guard()->login($user);
and make a guard function in same controller
protected function guard()
{
return Auth::guard();
}
import use Illuminate\Support\Facades\Auth; in top
include
use Illuminate\Support\Facades\Hash;
You need to make it with email not with username
$credentials = request(['email', 'password']);
OR, modify your attempt code
if(!Auth::attempt(['username' => $credentials['username'], 'password' => $credentials['password']))
this code worked with sanctum
use App\Models\User;
use Illuminate\Support\Facades\Hash;
function login($candidate)
{
$user = User::where('username', $candidate['username'])->first();
if (!$user || !Hash::check($candidate['password'], $user->password)) {
return [
'message' => 'These credentials do not match our records.'
];
}
$token = $user->createToken('my-token')->plainTextToken;
return [
'user' => $user,
'token' => $token
];
}

Laravel Vapor- Allow unauthenticated user perform an upload

By default Laravel Vapor requires the user be authenticated to perform an upload. I need to allow an unauthenticated perform an upload. How can I do this?
Thanks
I think if you add something like this in your UserPolicy, vapor should work
public function before($user)
{
if (Auth::guest()) {
return true;
}
}
We handled this by overriding the default vapor/signed-storage-url route's handling.
In routes/web.php.
Route::post('vapor/signed-storage-url', [Controllers\SignedStorageUrlController::class, 'store']);
In our SignedStorageUrlController, we use the store function with this check removed:
Gate::authorize('uploadFiles', [
$request->user(),
$bucket = $request->input('bucket') ?: $_ENV['AWS_BUCKET'],
]);
resulting in:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Laravel\Vapor\Http\Controllers\SignedStorageUrlController as VaporSignedStorageUrlController;
class SignedStorageUrlController extends VaporSignedStorageUrlController
{
public function store(Request $request)
{
$this->ensureEnvironmentVariablesAreAvailable($request);
$bucket = $request->input('bucket') ?: $_ENV['AWS_BUCKET'];
$client = $this->storageClient();
$uuid = (string) Str::uuid();
$signedRequest = $client->createPresignedRequest(
$this->createCommand($request, $client, $bucket, $key = ('tmp/'.$uuid)),
'+5 minutes'
);
$uri = $signedRequest->getUri();
return response()->json([
'uuid' => $uuid,
'bucket' => $bucket,
'key' => $key,
'url' => 'https://'.$uri->getHost().$uri->getPath().'?'.$uri->getQuery(),
'headers' => $this->headers($request, $signedRequest),
], 201);
}
}

Laravel 5.3: How to authenticate only active users

I want to laravel 5.3 loged in users table status='Active' but status='Inactive' can't loged in.
Please help me with that. Thanks a lot guys!
Go to \vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php
then change credentials functions.
And see this link https://laracasts.com/discuss/channels/laravel/allowing-only-active-users-to-login.
example function link
protected function credentials(Request $request)
{
$crendentials = $request->only($this->username(), 'password');
$crendentials['status']='Active';
return $crendentials;
}
Add this function in Auth/LoginController.php
use Illuminate\Http\Request;
protected function credentials(Request $request)
{
return [
$this->username() => $request->get($this->username()),
'password' => $request->get('password'),
'active' => 1
];
}
By doing this, you actually override it. This function is in the AuthenticatesUsers trait.
Another way for getting the same result is to override the validateLogin() function by adding
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => [
'required',
Rule::exists('users')->where(function ($query) {
$query->where('active', 1);
}),
],
'password' => 'required',
]);
}
to the LoginController.php
You can try like this:
if (Auth::attempt(['email' => $email, 'password' => $password, 'status' => 'Active'])) {
// The user is active, not suspended, and exists.
}

How to add extra logic on login condition in Laravel 5.2

I just wanted to say if the user is not active, don't allow to login. I have made the controller as below, I am not sure what I am missing or what else I have to do here to make this work!
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Auth\Authenticatable;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
public function authenticate()
{
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
}
My thinking was authenticate() method should do the trick!
The below code worked for my case:
protected function getCredentials(Request $request)
{
return [
'email' => $request->input('email'),
'password' => $request->input('password'),
'active' => true
];
}
for Laravel 5.3 need to add following code to LoginController
protected function credentials(Request $request)
{
return [
'email' => $request->input('email'),
'password' => $request->input('password'),
'active' => true
];
}
i think you should create method to check if user passed your credentials, here's my suggestion :
protected function getCredentials(Request $request)
{
return [
'username' => $request->input('email'),
'password' => $request->input('password'),
'active' => true
];
}
and your login method:
public function login(Request $request) {
$this->validate($request,['email' => 'required|email','password' => 'required']);
if (Auth::guard()->attempt($this->getCredentials($request))){
//authentication passed
}
return redirect()->back();
}
hope you get basic idea.
In LoginController.php file write this function
protected function credentials(Request $request) {
$extraFields = [
'user_type'=> 'customer',
'user_entry_status' => 1
];
return array_merge($request->only($this->username(), 'password'), $extraFields);
}
Go to this path :
your-project-folder/vendor/laravel/framework/src/illuminate/Foundation/Auth/AuthenticatesUsers.php
$credentials=$request->only($this->loginUsername(), 'password');
$credentials['status'] = '1';
return $credentials;
Change getCredantials works fine, but it is good practice to let user know, that the account was suspended (credentials are OK, but the account status is not). You can easily override login method in Auth/LoginController.php to your own copy, add your own logic to login process and raise own exception.
in Auth/LoginController.php create login and sendAccountBlocked function
/*load additional classes to LoginController.php*/
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Auth;
public function login(Request $request){
//
$this->validateLogin($request);
//
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if (method_exists($this, 'hasTooManyLoginAttempts') && $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
//check user status
if (Auth::user()->user_status == 'A') return $this->sendLoginResponse($request);
// if user_status != 'A' raise exception
else {
$this->guard()->logout();
return $this->sendAccountBlocked($request);
}
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
//
}//
protected function sendAccountBlocked(Request $request){
throw ValidationException::withMessages([
$this->username() => ['Your account was suspended.'],
]);
}

Resources