Laravel Using config() in request validation - php

I'm using laravel 5.8 and I want to use access global config() in Request validation class but it does not work
namespace App\Http\Requests;
use App\AppConstant;
use Illuminate\Foundation\Http\FormRequest;
class Something 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 [
'url' => 'required',
'category' => 'in:'.implode(",", config('app.categories').''
];
}
}
and here is part of my config/app.php
return [
'name' => env('APP_NAME', 'Laravel'),
'categories' => [
'games',
'entertainment'
],
but the output is
Class App\\Http\\Requests\\Something does not exist
when i remove config() from request file it works very well

your code is missing a close bracket ) after categories. it should be
'category' => 'in:'.implode(",", config('app.categories')).''

Related

Cant Access App\Filters directory CodeIgniter4

I'm trying to makes a JWT Filter with CI4, but when I about to set my filter in /Config/Filter.php it always says the class is not found although it definitely in the /App/Filters/ directory. I've been trying to make new directory in /App and named it AuthFilter still no luck
/Config/Filter.php :
<?php
namespace Config;
use App\Filters\FilterJwt;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Filters\CSRF;
use CodeIgniter\Filters\DebugToolbar;
use CodeIgniter\Filters\Honeypot;
use CodeIgniter\Filters\InvalidChars;
use CodeIgniter\Filters\SecureHeaders;
class Filters extends BaseConfig
{
/**
* Configures aliases for Filter classes to
* make reading things nicer and simpler.
*/
public array $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class,
'authentification' => FilterJwt::class
];
/**
* List of filter aliases that are always
* applied before and after every request.
*/
public array $globals = [
'before' => [
// 'honeypot',
// 'csrf',
// 'invalidchars',
],
'after' => [
'toolbar',
// 'honeypot',
// 'secureheaders',
],
];
/**
* List of filter aliases that works on a
* particular HTTP method (GET, POST, etc.).
*
* Example:
* 'post' => ['foo', 'bar']
*
* If you use this, you should disable auto-routing because auto-routing
* permits any HTTP method to access a controller. Accessing the controller
* with a method you don’t expect could bypass the filter.
*/
public array $methods = [];
/**
* List of filter aliases that should run on any
* before or after URI patterns.
*
* Example:
* 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
* #var array
*/
public $filters = [
'authentification' => [
'before' => [
'users/*',
'users'
]
]
];
}
/App/Filters/FilterJwt.php :
<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\API\ResponseTrait;
use Exeption;
class MyFilter implements FilterInterface
{
use ResponseTrait;
public function before(RequestInterface $request, $arguments = null)
{
$header = $request->getServer('HTTP_AUTHORIZATION');
try {
helper('jwt');
$encodedToken = getJwt($header);
checkJWT($encodedToken);
return $request;
} catch (Exeption $e) {
return Services::response()->setJson([
'error' => $e->getMessage()
])->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// Do something here
}
}
Proof that the file is in directory :
CI4 error:
As you can see, the CI4 cant find the "Filters" folder although its right there.
Rename your class from "MyFilter" to "FilterJwt".
Instead of:❌
/App/Filters/FilterJwt.php
class MyFilter implements FilterInterface
{
//...
Use this:✅
/App/Filters/FilterJwt.php
class FilterJwt implements FilterInterface
{
//...

Unique always return already taken in laravel validation

I'm trying to update a company data using CompanyRequest but got an error. Please see my code below and other details.
CompanyRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Validation\Rule;
use Illuminate\Foundation\Http\FormRequest;
class CompanyRequest 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()
{
if($this->isMethod('PATCH')) {
return [
'name' => [
'required',
'max:255',
Rule::unique('companies')->ignore($this->id)
],
'owner' => 'required|max:255',
'address' => ''
];
}
return [
'name' => 'required|max:255|unique:companies',
'owner' => 'required|max:255',
'address' => ''
];
}
}
CompanyController.php
public function update(Company $company, CompanyRequest $request)
{
return $company->update($request->validated());
}
api.php
Route::patch('company/{company}', [CompanyController::class, 'update'])->name('company.update');
Error
I think you need to use the same property as the route
Rule::unique('companies')->ignore($this->company)
Try something like
'name' => 'unique:companies,name,' . $id,
so basically name is unique, but allow update when id is same.
To tell the unique rule to ignore the user's ID, you may pass the ID as the third parameter:
'name' => 'unique:companies,column,'.$this->id

Hw can I get Url params (id for example) in request made by php artisan make:request

I want to create a Request made by php artisan make:request wherein rules I can add a param, for instance I have the following validator in the controller:
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:{{number}}',
'body' => 'required',
]);
Where number is from url parameter
How can I get this url parameter in my Request class?
Here is my Request class:
<?php
namespace Modules\Blog\Http\Requests;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
class SaveBlogCategoriesRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
dd($request->param);
return [
'lang' => 'required',
'name' => 'required',
'slug' => "required|unique:blog_categories_id,slug,", // here I want to add id from param
];
}
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
protected function failedValidation(Validator $validator)
{
$data = [
'status' => false,
'validator' => true,
'msg' => [
'e' => $validator->messages(),
'type' => 'error'
],
];
throw new HttpResponseException(response()->json($data));
}
}
For the request class, you dont need to instantiate the validator
class ModelCreateRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
//if you need the input, you can access it via $this->request;
$param = $this->request->get('param');
//or you can also access it directly (yeah I know it not intuitive)
$param = $this->param
return [
'lang' => 'required',
'name' => 'required',
'slug' => "required|unique:blog_categories_id,slug,".$param,
];
}
}
Use dd($this) to get the request object in request class

How to pass non required fields through FormRequest?

I'm using FormRequest for Validation.
I'm creating record in DB. There a some fields which are not required, how can i get them through FormRequest. At, the moment i'm only getting fields which are in rules() method.
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CategoryRequest 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 [
'title_tr' => 'required|min:2|max:255',
'description_tr' => 'required',
'parent_id' => 'required',
'seo_title_tr' => 'required',
'meta_description_tr' => 'required'
];
}
public function messages(){
return [
'title_tr.required' => trans('admin.category.validation_errors.title_tr'),
'description_tr.required' => trans('admin.category.validation_errors.description_tr'),
'seo_title_tr.required' => trans('admin.category.validation_errors.seo_title_tr'),
'meta_description_tr.required' => trans('admin.category.validation_errors.meta_description_tr'),
];
}
}
you can use sometimes
Validating When Present In some situations, you may wish to run
validation checks against a field only if that field is present in the
input array. To quickly accomplish this, add the sometimes rule to
your rule list:
public function rules()
{
return [
'username' => 'sometimes',
];
}
You can make it nullable as shown below.
public function rules()
{
return [
// ...
'not_required_field' => 'nullable',
];
}

Laravel custom request not found

I got my custom request RegisterRequest and I'm trying to use it but for some reason I always get this error like i'm not including it:
ReflectionException in RouteSignatureParameters.php line 25:
Class App\Http\Controllers\RegisterRequest does not exist
this is my request:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RegisterRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'username' => 'required',
'email' => 'required',
'emailconfirm' => 'required',
'password' => 'required',
'passwordconfirm' => 'required',
];
}
public function messages(){
return [
'username.required' => 'Username is required',
],
}
}
and this is how i'm trying to use it:
use App\Http\Requests\RegisterRequest;
and in my method:
public function RegisterPost(RegisterRequest $request){
return response()->json($request->all(),200);
}
I always get 500 internal server error with message that request does not exists.
This command may help:
composer dump-autoload

Categories