Form Request Rule in Laraval 7 Not Working - php

I'm using laravel 7
I have a Request that I've built but the required rule is not working. Request sends back without any error.
and dd() also not showing request data.
Function:
public function store(StoreRequest $request)
{
dd($request->all());
if (!auth()->user()->can('add-users')) {
abort(401);
}
try {
$userStatus = app(CreateUser::class)->execute($request->all());
if ($userStatus == true) {
return redirect()->back()->with('success', 'User successfully created.');
} else {
return redirect()->back()->with('error', 'Oops Something went wrong!');
}
} catch (\Exception $ex) {
return redirect()->back()->with('error', $ex->getMessage());
}
}
Request Code:
class StoreRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => ['required','string','max:255'],
'email' => ['required','string','max:255'],
'password' => 'required',
'organization_id' => 'required'
];
}
}
If I use Illuminate\Http\Request showing the request data but not validating the data.
Any idea?

Please can you try this
public function rules()
{
return [
'name' => 'required|string|max:255',
'email' => 'required|string|max:255',
'password' => 'required',
'organization_id' => 'required'
];
}

Related

problem when using policy with laravel spatie

i have using laravel spatie for permission management: and it is not working with policy, I tried this:
in UserPolicy:
public function view(User $user, User $model)
{
if($user->can('display')) {
return true;
}
}
in controller UserController:
public function index()
{
$this->authorize('view', Auth::user());
$users = User::paginate(10);
return view('users.index', compact('users'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$permissions = Permission::all();
return view('users.create', compact('permissions'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name' => ['required', 'min:3'],
'email' => ['email', 'required', 'unique:users'],
'password' => ['required', 'confirmed', 'min:6'],
]);
try {
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
$user->syncPermissions($request->permissions, []);
return redirect()->route('users.index')->with('msg', 'user has created successfully');
}catch(\Exception $e) {
return redirect()->back()->with('msg', 'User not registered');
}
}
I have tried index function with user has many permissions including (display) and show me the (Forbbeden page) for all users even with display permission

Validation in Laravel 8

I´m trying to create a personalized request in Laravel 8.
class SendContactFormRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|min:4|max:30',
'email' => 'required|email',
'phone' => 'required|numeric|size:11',
'message' => 'required|min:4|max:400',
];
}
}
In my controller i´m using it to send email.
public function sendContactForm(SendContactFormRequest $request)
{
try {
$data = [
'name' => $request->get('name'),
'email' => $request->get('email'),
'phone' => $request->get('phone'),
'message' => $request->get('message'),
];
// SEND EMAIL
$this->sendNotification($data);
return redirect()
->back()
->with('success', trans('web.'));
} catch (Exception $e) {
return redirect()
->back()
->with('danger', $e->getMessage());
}
}
But always return HTTP ERROR 500 i don´t know what I´m doing wrong... I´m watching any tutorials and any code example, but I don´t know what it´s my problem.
UPDATED
Finally i did this:
firt i´m creating one personalised request:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SendContactFormRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|string|max:20',
'email' => 'required|email|unique:users,email',
'phone' => 'required|numeric|min:10',
'message' => 'required|string|max:400',
];
}
}
in my controller i add use and create object in function:
public function sendContactForm(SendContactFormRequest $request)
{
try{
$data = [
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'message' => $request->message,
];
// SEND EMAIL
$this->sendNotification($data);
return redirect()
->back()
->with('success', trans('web.'));
}catch (Exception $e) {
return redirect()
->back()
->with('danger', $e->getMessage());
}
}
now i´m user $request->variable before i´m using $request->get() i configure my notification and send my email ok.
Now my problem it´s that i tray send my contact form empty, i can´t show messages... But now i can see i my apache log, that i have this:
[
Mon May 03 17:55:48.109395 2021] [php:error] [pid 9796:tid 1216] [client ::1:61899] PHP Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 262144 bytes) in C:\\wamp64\\www\\aeveWeb\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Bootstrap\\HandleExceptions.php on line 129, referer: http://aeveweb.local/contact
i incremented this value to 512MB in wampServer but same result. I think that my code not validate my form, but i don´t understand i don´t know that i´m doin wrong
update
function sendNotification
/**
* SEND NOTIFICATION WHEN CONTACT FORM IT´S SEND
*/
public function sendNotification($data)
{
$emailTo = "";
$details = [
'name' => $data["name"],
'email' => $data["email"],
'phone' => $data["phone"],
'message' => $data["message"],
];
Notification::route('mail', $emailTo)->notify(new newMessage($details));
return redirect()->back()->with('success', 'Notificación enviada');
}
i resolve my question with:
$data = [
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'message' => $request->message,
];
$validator = Validator::make($data,[
'name' => 'required|string|min:3|max:125',
'email' => 'required|string|email|max:100',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:9',
'message' => 'required|string|max:400'
]);
if ($validator->fails()) {
return back()->withErrors($validator);
}else{
// SEND EMAIL
$this->sendNotification($data);
return redirect()
->back()
->with('success', trans('web.contact_form_send'));
}

Getting user data with Laravel Sanctum

I was using Laravel's built-in api token authentication before but I wanted to provide multiple api tokens for different clients and with Laravel 7.x, I'm trying to migrate to Laravel Sanctum.
API seems authenticates user without any problem but when I try to get user data with Auth::user();, it returns null. Also  Auth::guard('api')->user(); returns null too.
What should I use as Auth guard? Or is it correct way to get user data based on provided token?
Thank you very much....
auth('sanctum')->user()->id
auth('sanctum')->check()
without middleware, you could use these.
First, route through the sanctum auth middleware.
Route::get('/somepage', 'SomeController#MyMethod')->middleware('auth:sanctum');
Then, get the user.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function MyMethod(Request $request) {
return $request->user();
}
}
auth()->user() is a global helper, Auth::user() is a support facade, and $request->user() uses http. You can use any of them.
For a quick test, try
Route::get('/test', function() {
return auth()->user();
})->middleware('auth:sanctum');
Be sure to send your token in a header like so:
Authorization: Bearer UserTokenHere
Send token in the Authorization header, below code return the auth user.
Route::middleware('auth:sanctum')->group(function () {
Route::get('/profile/me', function (Request $request) {
return $request->user();
});
});
In case of restful api, suggest you to send Accept header also for checking at authenticate middleware for redirection if not authenticated. By default for restful api it redirect to login form (if any) if user not authenticated.
namespace App\Http\Middleware;
protected function redirectTo($request)
{
if (!$request->expectsJson()) {
return route('login');
}
}
When you are logging in the user, in your login function use something like this
public function login(Request $request)
{
if(Auth::attempt($credentials))
{
$userid = auth()->user()->id;
}
}
Then send this user id to the client and let it store in a secured way on client-side. Then with every request, you can use this user-id to serve data for next requests.
private $status_code= 200; // successfully
public function register(Request $request)
{
// $validator = $this->validator($request->all())->validate();
$validator = Validator::make($request->all(),
[
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255'], // , 'unique:users'
'password' => ['required', 'string', 'min:4'],
]
);
if($validator->fails()) {
return response()->json(["status" => "failed", "message" => "Please Input Valid Data", "errors" => $validator->errors()]);
}
$user_status = User::where("email", $request->email)->first();
if(!is_null($user_status)) {
return response()->json(["status" => "failed", "success" => false, "message" => "Whoops! email already registered"]);
}
$user = $this->create($request->all());
if(!is_null($user)) {
$this->guard()->login($user);
return response()->json(["status" => $this->status_code, "success" => true, "message" => "Registration completed successfully", "data" => $user]);
}else {
return response()->json(["status" => "failed", "success" => false, "message" => "Failed to register"]);
}
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
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:4'],
]);
}
/**
* Create a new user instance after a valid registration.
* #author Mohammad Ali Abdullah ..
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
protected function guard()
{
return Auth::guard();
}
/**
* method public
* #author Mohammad Ali Abdullah
* #date 01-01-2021.
*/
public function login(Request $request)
{
$validator = Validator::make($request->all(),
[
"email" => "required|email",
"password" => "required"
]
);
// check validation email and password ..
if($validator->fails()) {
return response()->json(["status" => "failed", "validation_error" => $validator->errors()]);
}
// check user email validation ..
$email_status = User::where("email", $request->email)->first();
if(!is_null($email_status)) {
// check user password validation ..
// ---- first try -----
// $password_status = User::where("email", $request->email)->where("password", Hash::check($request->password))->first();
// if password is correct ..
// ---- first try -----
// if(!is_null($password_status)) {
if(Hash::check($request->password, $email_status->password)) {
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed ..
$authuser = auth()->user();
return response()->json(["status" => $this->status_code, "success" => true, "message" => "You have logged in successfully", "data" => $authuser]);
}
}else {
return response()->json(["status" => "failed", "success" => false, "message" => "Unable to login. Incorrect password."]);
}
}else{
return response()->json(["status" => "failed", "success" => false, "message" => "Email doesnt exist."]);
}
}
public function logout()
{
Auth::logout();
return response()->json(['message' => 'Logged Out'], 200);
}
I see that no answer has been accepted yet. I just had the problem that my sacntum auth did not work. The auth() helper always returned null.
To solve the problem I removed the comment in the kernel.php under the api key. It is about this class \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class. This is because it is commented out by default.
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
After that I had access to the User object with the auth() helper.
The simplest way to to that is to use auth helpers like
$user = auth('sanctum')->user();
Or you can get it by the request object
//SomeController.php
public function exampleMethod(Request $request)
{
$user = $request->user();
}
To get user by sactum token string like
2|bTNlKViqCkCsOJOXWbtNASDKF7SyHwzHOPLNH
Code be like
use Laravel\Sanctum\PersonalAccessToken;
//...
$token = PersonalAccessToken::findToken($sactumToken);
$user = $token->tokenable;
Note: The most way to pass token is from Authorization headers by bearer
Make sure the sanctum middleware is in api
I was in the same boat; migrated to Sanctum and wondered why all of my $request->user() were empty. The solution for me was to throw some middleware onto the stack to modify the request's user() resolver:
namespace App\Http\Middleware;
use Illuminate\Http\Request;
class PromoteSanctumUser
{
/**
* #param Request $request
* #param \Closure $next
*/
public function handle(Request $request, \Closure $next)
{
$sanctumUser = auth('sanctum')->user();
if ($sanctumUser) {
$request->setUserResolver(function() use ($sanctumUser) {
return $sanctumUser;
});
}
return $next($request);
}
}

Laravel - Sending Mail Returns Error Cannot Return Property of Non Object

I have this very strange problem, where when I send an email view in the build method of a mailable, it sends fine, but error's "Trying to get property 'view' of non-object", and thus I can't redirect to a page after sending the mail.
Mailable:
public function __construct($data)
{
$this->email = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$url = URL::temporarySignedRoute(
'verifyCustomer', now()->addMinutes(100),['email'=>$this->email]
);
return $this->from('support#xxxx.com')
->view('validate_email')->with([
'url' => $url,
'email' => $this->email
]);
dd('doesent work here');
}
Register controller:
protected function createCustomer(Request $request)
{
// dd($request->all());
// $this->validator($request->all())->validate();
$validator = Validator::make($request->all(), [
'name' => ['required', 'alpha_dash', 'string', 'max:25', 'unique:customers'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:customers'],
'password' => ['required', 'string', 'min:6', 'confirmed'],
]);
if ($validator->fails())
{
$messages = $validator->messages();
return Redirect::back()->withErrors($validator)->withInput();
foreach($errors->all() as $error) {
echo $error;
}
}
elseif ($validator->passes())
{
$customer = customer::create([
'name' => $request['name'],
'email' => $request['email'],
'password' => Hash::make($request['password']),
'VerifyToken' => Str::random(40),
]);
$customer->SendEmailVerificationNotification();
return redirect()->intended('auth/login');
}
}
SendEmailVerificationNotification:
class SendEmailVerificationNotification
{
/**
* Handle the event.
*
* #param \Illuminate\Auth\Events\Registered $event
* #return void
*/
public function handle(Registered $event)
{
if ($event->user instanceof MustVerifyEmail && ! $event->user->hasVerifiedEmail()) {
$event->user->sendEmailVerificationNotification();
}
}
}
sendEmailVerification function:
public function sendEmailVerificationNotification()
{
$this->notify(new \App\Notifications\account_verification_notification);
}
account_verification_notification:
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
Mail::to($notifiable['email'])->send(new validate_email($notifiable['email']));
// return (new MailMessage)
// ->line('The introduction to the notification.')
// ->action('Notification Action', url('/'))
// ->line('Thank you for using our application!');
}
Any help would be absolutely fantastic! As this is the third day struggling with this bug :(
Thankyou :)

dingo api validator rule need to fix

public function store(Request $request) {
$response = array('response' => '', 'success'=>false);
$rules = [
'email' => 'required|email',
'password' => 'required'
];
$validator = \Validator::make($request->all(), $rules);
if($validator->fails()){
$response['response'] = $validator->messages();
return $this->response->error($response, 401);
// or
return $this->response->error($validator, 401);
}else{
User::create($request->all());
}
}
How can I set validator in laravel using dingo API? I tried above code but does not work can't understand where is the right reference to keep track error logs
Please guide.
$rules = [
'username' => 'required',
'password' => 'required'
];
$payload = app('request')->only('username', 'password');
$validator = app('validator')->make($payload, $rules);
if ($validator->fails()) {
throw new Dingo\Api\Exception\StoreResourceFailedException('Invalid username provided.', $validator->errors());
}
You can try this
public function store()
{
$rules = [
'email' => 'required|email',
'password' => 'required'
];
$payload = app('request')->only('username', 'password');
$validator = app('validator')->make($payload, $rules);
if ($validator->fails()) {
throw new Dingo\Api\Exception\StoreResourceFailedException('Could not create new user.', $validator->errors());
}
User::create($request->all());
// send a success response
}
This example is taken from the documentation of Dingo and customized based on your code.
The best way I've found to do validation especially when using Dingo API is to use Form Requests.
When using Dingo API however, you use
use Dingo\Api\Http\FormRequest;
instead of
use App\Http\Requests\Request;
like in normal form requests.
So in your case, you'd have a form request like
<?php
namespace App\Http\Requests;
use Dingo\Api\Http\FormRequest;
class CreateUser extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'email' => 'required|email',
'password' => 'required'
];
}
}
So this keeps validations outside your controller. And your controller function can just be
public function store(Request $request) {
User::create($request->all());
}
If you are not very familiar with Form Requests, this is a great chance to look at it. Cheers.

Categories