Class App\Http\Request\CreatePost does not exist - php

this CreatePost.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CreatePost 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' => 'required|string',
'content' => 'required',
];
}
}
anyone please help me ?? Class App\Http\Request\CreatePost does not exist
thank

you need to import the model on top
for example
use App\Supplier;

Related

Laravel 9 Accessor not Returning Value

I have a Reminder model that has a sound_path column. I created an accessor for that column in the model but it's returning null and I doubled checked that the database has a value in that column. What am I doing wrong?
Note: Of course I can call $this->sound_path directly in soundPathUrl mutator without creating the accessor from the first place but I'm interested to know why if I called the accessor is not returning any value.
Reminder model
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Spatie\Translatable\HasTranslations;
class Reminder extends BaseModel
{
use HasFactory, SoftDeletes, HasTranslations;
public $translatable = [
'title__ml',
];
protected $casts = [
'available_days_for_reminder' => 'json',
'is_multiple_days_allowed' => 'boolean'
];
protected $appends = ['sound_path_url'];
/**
* Get the sound path
*
* #param string $value
* #return \Illuminate\Database\Eloquent\Casts\Attribute
*/
protected function soundPath(): Attribute
{
return Attribute::make(
get: fn ($value) => $value
);
}
/**
* Get sound path download URL
*
* #return \Illuminate\Database\Eloquent\Casts\Attribute
*/
protected function soundPathUrl(): Attribute
{
return new Attribute(
get: fn () => asset('storage/' . $this->soundPath),
);
}
}
Reminder controller
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Resources\Reminder\ReminderCollection;
use App\Http\Resources\Reminder\ReminderResource;
use App\Models\Reminder;
use Exception;
use Illuminate\Http\Request;
class ReminderController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$reminders = Reminder::paginate(5);
return ReminderCollection::collection($reminders);
}
}
ReminderCollection API resource
namespace App\Http\Resources\Reminder;
use Illuminate\Http\Resources\Json\JsonResource;
class ReminderCollection extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title__ml,
'sound' => $this->sound_path_url
];
}
}
Screenshot of Response
At the arrow there should be the value of sound_path.
Your issue is that you are calling $this->soundPath instead of $this->sound_path in soundPathUrl method...
So, you should have this:
/**
* Get sound path download URL
*
* #return \Illuminate\Database\Eloquent\Casts\Attribute
*/
protected function soundPathUrl(): Attribute
{
return new Attribute(
get: fn () => asset('storage/' . $this->sound_path),
);
}
Check the documentation and you will see you still have to call your properties using snake_case.
It seems soundPath accessor does nothing, it returns the same value which seems empty. Where does soundPath value come from? First, make sure, soundPath itself has any value within that function.
Call soundPath as a function
protected function soundPathUrl(): Attribute
{
return new Attribute(
get: fn () => asset('storage/' . $this->soundPath()),
);
}
}

Test laravel sanctum with tokens

I would like to test if a user is logged out,I am using Sanctum with Laravel Breeze, I am trying like this:
public function test_users_can_logout()
{
$this->signIn();
$response = $this->postJson(
'/api/logout'
);
$this->assertGuest();
}
And this is AuthenticatedSessionController .php, This came from Breeze, I modified it:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
class AuthenticatedSessionController extends Controller
{
/**
* Handle an incoming authentication request.
*
* #param \App\Http\Requests\Auth\LoginRequest $request
* #return \Illuminate\Http\RedirectResponse
*/
public function store(LoginRequest $request)
{
$request->authenticate();
$token = $request->user()->createToken('MyAuthApp')->plainTextToken;
return response()->json(
[
'access_token' => $token,
'token_type' => 'Bearer',
'user' => $request->user()
]
);
}
/**
* Destroy an authenticated session.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function destroy(Request $request)
{
$request->user()->tokens()->delete();
return response()->json(
[
'message' => 'log out successfully'
]
);
}
}
LoginRequest.php
<?php
namespace App\Http\Requests\Auth;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class LoginRequest 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|string|email',
'password' => 'required|string',
];
}
/**
* Attempt to authenticate the request's credentials.
*
* #return void
*
* #throws \Illuminate\Validation\ValidationException
*/
public function authenticate()
{
$this->ensureIsNotRateLimited();
if (! Auth::attempt($this->only('email', 'password'), $this->filled('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => __('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
/**
* Ensure the login request is not rate limited.
*
* #return void
*
* #throws \Illuminate\Validation\ValidationException
*/
public function ensureIsNotRateLimited()
{
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
return;
}
event(new Lockout($this));
$seconds = RateLimiter::availableIn($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.throttle', [
'seconds' => $seconds,
'minutes' => ceil($seconds / 60),
]),
]);
}
/**
* Get the rate limiting throttle key for the request.
*
* #return string
*/
public function throttleKey()
{
return Str::lower($this->input('email')).'|'.$this->ip();
}
}
TestCase.php
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Laravel\Sanctum\Sanctum;
use App\Models\User;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
protected function signIn($user = null)
{
$user = $user ?: User::factory()->create();
Sanctum::actingAs($user);
return $user;
}
}
EDITED: now I am testing only the logout route, my test fails, maybe because sanctum is using cookies? is it ok use sanctum with breeze?
I would like to test if the token no longer exists, what can I do?

Renaming laravel validation array notation in error messages

I am getting a very unfriendly field name in my validation errors similar to the array notation used as name for the field's rules
EG.
$rules = [
'resource.*.name' => 'required|string|max:16'
];
// error message.
// the resource.0.name is required.
How do I rename the resource.0.name in the message to something else like name or resource name.
For more convenience you may use laravels form request validation,
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class Resource 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 [
'resource.*.name' => 'required|string|max:16'
];
}
public function messages()
{
return [
'resource.*.name' => 'The Resouce Name must match the criteria'
];
}
}
In your controller:
use App\Http\Requests\Resource;
public function store(Resource $request)
{
}

Laravel 5.3 dynamically binding validator to custom form request

I'm developing in a system using Laravel 5.3 and I"m trying to update custom validation rules. The architecture is currently as follows:
ProfileStoreRequest --> ProfileValidator
ClientStoreRequest --> ClientValidator
...
What I'm basically trying to do here is to have only one object named "StoreRequest" which will call the correct validator depending on the route which is being called. Here's what I have so far:
In my routes:
Route::group([
'prefix' => 'manage',
'namespace' => 'Manage',
'validators' => [
'manage.profile.storeAjax' => [
'name' => "required|max:40",
'color' => "integer|digits_between:0,7",
'service' => "integer", //digits_between:3,10
'company_id' => "required|integer|exists:companies,id,deleted_at,NULL",
'site_id' => "integer|siteIdExists"
]
]], function () {
Route::post('/site/storeAjax', 'SiteController#storeAjax')->name('manage.site.storeAjax');
Route::post('/company/storeAjax', 'CompanyController#storeAjax')->name('manage.company.storeAjax');
Route::post('/employee/store', 'EmployeeController#store')->name('manage.employee.store');
Route::post('/employee/addProfile', 'EmployeeController#addProfile')->name('manage.employee.addProfile');
Route::post('/employee/removeProfile', 'EmployeeController#removeProfile')->name('manage.employee.removeProfile');
Route::post('/employee/addSite', 'EmployeeController#addSite')->name('manage.employee.addSite');
Route::post('/employee/removeSite', 'EmployeeController#removeSite')->name('manage.employee.removeSite');
Route::post('/message/storeAjax', 'MessageController#storeAjax')->name('manage.message.storeAjax');
Route::post('/profile/storeAjax', 'ProfileController#storeAjax')->name('manage.profile.storeAjax');
Route::post('/timeEntry/storeAjax', 'TimeEntryController#storeAjax')->name('manage.timeEntry.storeAjax');
});
Next is my StoreRequest:
namespace App\Http\Requests;
use App\Http\Validators\ProfileValidator;
use Auth;
//use App\Model\TimeEntry;
use DateUtil;
use Illuminate\Contracts\Validation\Factory as ValidationFactory;
class StoreRequest extends AbstractRequest {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize() {
// prj(__METHOD__);
$authorized = parent::authorize();
if ($authorized) {
$user = Auth::user();
if ($user && $user->can('write')) {
return true;
} else {
return false;
}
}
return false;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules() {
parent::rules();
return $this->route()->getAction()['validators'][$this->route()->getName()];
}
/**
* User messages
*
* #return array
*/
public function messages() {
$messages = array_merge(parent::messages(), [
'exists' => 'The selected :attribute is invalid for this time entry id.'
]);
return $messages;
}
public function validate()
{
parent::validate();
}
}
And of course, all of my custom validators are registered using service providers (here's an example with a profileValidator):
profileServiceProvider.php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Validator;
class ProfileServiceProvider extends ServiceProvider {
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot() {
Validator::extend('siteIdExists', 'App\Http\Validators\ProfileValidator#validateSiteIdExists');
}
/**
* Register any application services.
*
* #return void
*/
public function register() {
//
}
}
ProfileValidator.php
namespace App\Http\Validators;
use App\Model\Site;
use Mockery\Exception;
class ProfileValidator
{
public function validateSiteIdExists($attribute, $value, $parameters, $validator)
{
if ($value == -1)
return true;
else
{
return Site::where(
[
['id', '=', $value],
['company_id', '=', $validator->getData()['company_id']]
]
)->whereNull('deleted_at')->exists();
}
}
}
So basically, my StoreRequest is capable of loading its validation rules from the route... however, no matter how hard I try, I can't figure how to bind the validator I want. Can anyone help me?

How to add custom validation rule into laravel 5.2?

I try to add new validation rule (Laravel 5.2) for google recaptcha and this rule not working. Can you explain me why? And how to fix it?
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Validator;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Validator::extend('recaptcha', function($attribute, $value, $parameters, $validator) {
return false;
});
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}
-
class AuthController extends Controller
{
/**
* 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, [
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
'g-recaptcha-response' => 'recaptcha|required',
]);
}
Require rule working fine, recaptcha not.
I try to do dump-autoload - no results.
Thank you very much :)
change recpatcha|required to captcha|required
assuming you're using https://github.com/anhskohbo/no-captcha

Categories