I have simple function for check sender email.
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
protected function validator(array $data)
{
return Validator::make($data, [
'recipient' => 'required|email|exists:users,email',
'sender' => [
'required',
Rule::exists('users')->where(function ($query) {
$query->where('email', Auth::user()->email);
}),
],
], $this->validator_messages());
}
Why not work this code? I only must check sender email with auth user email.
You don't need to make a query in DB, because auth()->user() object is already loaded. So, you could use the In rule:
'sender' => [
'required',
Rule::in([auth()->user()->email]),
],
],
I think you must create a rule class for validation for example:
php artisan make:rule TestUserRule
And in this class implement 2 method : passes($attribute, $value) and message methods.
For example:
public function passes($attribute,$value){
//write your conditions here you must return boolean value here
return User::where('email',Auth::user()->email)->count();
}
Or you can use laravel default exists validation rule
Related
This described in the class Laravel\Fortify\Http\Requests\LoginRequest
I want to add one more validation line
namespace Laravel\Fortify\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Laravel\Fortify\Fortify;
class LoginRequest extends FormRequest
{
/..
public function rules()
{
return [
Fortify::username() => 'required|string',
'password' => 'required|string',
];
}
}
But I cannot do the customizations in the vendor.
My question is how to do this?
Just to add to the comment above, it's a bad idea to make changes in the vendor folder as stated earlier. For one, any code pushes to a repository will not reflect these changes (unless you modify the ignore file).
For Laravel/Fortify adding new fields and changing the default validation rules, even the password requirements is very straightforward. It's not clear to me what your requirement is, but it might be easier to simply use a Validator. That is what Fortify uses as well. For example, Fortify publishes two files:
App\Actions\Fortify\CreateNewUser.php
App\Actions\Fortify\PasswordValidationRules.php
To add a new validation rule for a field, simply add it the CreateNewUser.php under the Validator::make method that Fortify itself is using. You can follow the same logic in your custom implementation. For example to add a firstname field, modify as follows:
Validator::make($input, [
'firstname' => ['required', 'string', 'max:255'],
])->validate();
return User::create([
'firstname' => $input['firstname'],
]);
You can add as many field as you want. To change the password requirements, make changes to the passwordRules() function in the PasswordValidationRules.php file as follows:
protected function passwordRules()
{
return ['required',
'string',
(new Password)->requireUppercase()
->length(10)
->requireNumeric()
->requireSpecialCharacter(),
'confirmed'];
}
All this info can be found at the official docs https://jetstream.laravel.com/1.x/features/authentication.html#password-validation-rules
In short, I solved the problem like this
copy vendor\laravel\fortify\src\Http\Controllers\AuthenticatedSessionController.php to
app\Http\Controllers\Auth\LoginController.php (change namespace and class name)
copy vendor\laravel\fortify\src\Http\Requests\LoginRequest.php to app\Http\Requests\LoginFormRequest.php (change namespace and class name)
add new route in routes/web.php
use App\Http\Controllers\Auth\LoginController;
//
Route::post('/login', [LoginController::class, 'store'])
->middleware(array_filter([
'guest',
$limiter ? 'throttle:'.$limiter : null,
]));
in LoginController changed LoginRequest to LoginFormRequest and
public function store(LoginFormRequest $request)
{
return $this->loginPipeline($request)->then(function ($request) {
return app(LoginResponse::class);
});
}
in LoginFormRequest add my new rule(s)
public function rules()
{
return [
Fortify::username() => 'required|string',
'password' => 'required|string',
'myNewRule' => 'required|string',
];
}
Here's how you can use your own validation rules when authenticating with Fortify:
Create a file LoginRequest.php in App\Http\Requests that extends Fortify's LoginRequest.php class
I would just copy that class and update the namespace:
namespace App\Http\Requests;
use Laravel\Fortify\Http\Requests\LoginRequest as FortifyLoginRequest;
use Laravel\Fortify\Fortify;
class LoginRequest extends FortifyLoginRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
Fortify::username() => 'required|string',
'password' => 'required|string',
'myAttribute' => 'rules' // Customizations...
];
}
}
Add a binding in your AppServiceProviders.php boot method to resolve Fortify's class with your own:
public function boot()
{
$this->app->bind('Laravel\Fortify\Http\Requests\LoginRequest', \App\Http\Requests\LoginRequest::class);
}
I've found that page: https://dev.to/aibnuhibban/login-customization-in-laravel-8-2gc8
Go to vendor > laravel > fortify > src > Rule > Password.php
There you can change those config.
I need to check if I have all posted variables are required or else throw error.
Till Now I am doing like this
Routes.php
Route::post('/api/ws_fetchuser', 'UserController#fetch_user_details');
UserController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
public function fetch_user_details(Request $request)
{
if(!empty($request) && $request->id!='')
{
print_r($request->id);
}
else
{
return response(array(
'error' => false,
'message' =>'please enter all form fields',
),200);
}
}
}
I am checking like this $request->id!='', is there any validation rules or methods which I can use to check id is required field.
I have added this validation in my controller as well but what if id is not present how can I show the error?
Updated Validation Code:
public function fetch_user_details(Request $request)
{
$this->validate($request, [
'id' => 'required'
]);
print_r($request->id);
}
$this->validate() methods designed to redirect back when validation failed, So instead of that you can create a validator instance and get the error list manually.
use Validator;
$validator = Validator::make($request->all(), [
'id' => 'required'
]);
if ($validator->fails()) {
return json_encode($validator->errors()->all());
}
Hello I'm trying to create a code generator to invite a user from input email, I want to save on the database the user id who send the invite, the code, and the email who is going to recive the invite, but I can't get the id of my auth user doing $request->user('id') (not working) also I know there is other method to do this easier than using DB::table something like
$request->user()->invites()->create... my controller looks like
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class invitacionController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index(Request $request)
{
return view('administrar');
}
public function invitacion(Request $request)
{
$this->validate($request, [
'email' => 'required|email|max:255|unique:invites',
]);
/*$request->user()->invites()->create([
'code' => str_random(40),
]);*/
DB::table('invites')->insert([
['usuId' => $request->user('id'), 'code' => str_random(40), 'email' => $request->input('email')],
]);
return redirect('/administrar');
}
}
If the relationship is properly configured, the first (commented) method should be working.
As for the second method, I think you are adding extra brackets:
DB::table('invites')->insert([
'usuId' => $request->user()->id, // <---
'code' => str_random(40),
'email' => $request->input('email')
]);
That hasMany method can take additional parameters. By default it expects the column to be named user_id, but you called it usuId. The documentation gives this example:
return $this->hasMany('App\Comment', 'foreign_key');
So I think you should do
public function invites()
{
return $this->hasMany(Invite::class, 'usuId');
}
Hey guys I'm trying to learn PHP frameworks as well as OOP and I'm using Laravel 5.1 LTS.
I have the following code in my AuthController
<?php
namespace App\Http\Controllers\Auth;
use App\Verification;
use Mail;
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;
private $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
protected function create(array $data){
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
// generate our UUID confirmation_code
mt_srand((double)microtime()*15000);//optional for php 4.2.0 and up.
$charid = strtoupper(md5(uniqid(rand(), true)));
$uuid = substr($charid, 0, 8)
.substr($charid, 8, 4)
.substr($charid,12, 4)
.substr($charid,16, 4)
.substr($charid,20,12);
$data['confirmation_code'] = $uuid;
// pass everything to the model here
$setVerification = new Verification();
$setVerification->setVerificationCode($data['email'], $data['confirmation_code']);
// send email for confirmation
Mail::send('email.test', $data, function ($m) use ($data){
$m->from('test#test.com', 'Your Application');
$m->to($data['email'])->subject('Thanks for register! Dont forget to confirm your email address');
});
return $user;
}
}
my error message Class 'Models\Verification' not found is coming from this piece of code here
// pass everything to the model here
$setVerification = new Verification();
$setVerification->setVerificationCode($data['email'], $data['confirmation_code']);
which looks right to my beginner's eyes, but it's clearly wrong.
Here is my Verification class that has the setVerificationCode method
<?php
namespace App\Http\Controllers;
use App\User;
use DB;
use App\Http\Controllers\Controller;
class Verification {
/**
* This method will update the confirmation_code column with the UUID
* return boolean
**/
protected function setVerificationCode($email, $uuid) {
$this->email = $email;
$this->uuid = $uuid;
// check to see if $email & $uuid is set
if (isset($email) && isset($uuid)) {
DB::table('users')
->where('email', $email)
->update(['confirmation_code' => $uuid]);
return TRUE;
} else {
return FALSE;
}
}
/**
* This method will validate if the UUID sent in the email matches with the one stored in the DB
* return boolean
**/
protected function verifyConfirmationCode() {
}
}
Please give the following in AuthController
use App\Http\Controllers\Verification;
instead of
use App\Verification;
If we give use App\Verification , it will check if there is any model named Verification.
its seems that, you are missing something, which, Extend your Model with eloquent model
use Illuminate\Database\Eloquent\Model;
class Verification extends Model
{
and the rest is seems fine.
also share your verification model code
Updated
instead of your this line
use App\Verification;
do this
use App\Models\Verification;
as you created custom directory for your Models then its better to auto load it in your composer.json file. add this line "app/Models" in your "autoload" section. follow this
"autoload": {
"classmap": [
"database",
"app/Models"
],
and after that, run this command in your project repo composer dump-autoload
How to override Laravel 5.1 auth attempt with extra parameters using default auth controller and middleware?
suppose I have an extra field with status =active or inactive.
How can I write that attempt method?
As specified in the documentation you can pass an array of variables, with their keys being the columns you want to verify the values against in the database.
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Routing\Controller;
class AuthController extends Controller {
public function authenticate(Request $request)
{
$attempt = Auth::attempt([
'email' => $request->get('email'),
'password' => $request->get('password'),
'active' => $request->get('active')
]);
if ($attempt) {
return redirect()->intended('dashboard');
}
}
}