Request not found error in laravel controller - php

I have Laravel version 5.3 and i created a file createArticleRequest.php under the request folder , which looks like below:
<?php namespace App\Http\Requests;
use App\Http\Requests\Request;
class CreateArticleRequest extends Request {
public function authorize() {
return true;
}
public function rules() {
return [
'title' => 'required|min:3',
'body' => 'required',
'published_at' => 'required|date',
]
}
}
?>
In My articles controller i have the following method:
public function store(CreateArticleRequest $request) {
// $input = Request::all();
Article::create($request->all());
return redirect('articles');
}
But when i fill the form in my view and click on submit i get an error like so:
ReflectionException in Route.php line 286:
Class App\Http\Controllers\CreateArticleRequest does not exist
Why am i getting this error ??
I believe my articles Controller and my createArticlesRequest are in the same namespace so why am i getthing this error?

You should use PHP' use keyword at the top of the PHP file, so that php can find the CreateArticleRequest package Class in the right namespace like this:
namespace App\Http\Controllers;
use App\Http\Requests\CreateArticleRequest;
class Controller {
public function store(CreateArticleRequest $request) {
// $input = Request::all();
Article::create($request->all());
return redirect('articles');
}
}
Hope this helps!

Related

How to create custom validation rule in Laravel 6 API

I need to use my custom validation rule for validating API requests.
Request Class:
This is my request validation rule.
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class LoginRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'username' => 'required',
'password' => 'required'
];
}
public function messages()
{
return [
'username.required' => 'The Username field is required',
'password.required' => 'The Password field is required'
];
}
}
API Controller:
This is my API controller and method.
use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\LoginRequest;
class LoginController extends BaseController
{
public function login(LoginRequest $request)
{
print_r($validatorMsg);
die();
}
}
Unable to get error message.
guys, I resolved the problem this is the solution:
public function login(Request $request)
{
$LoginRequest = New LoginRequest;
$validator = Validator::make($request->all(), $LoginRequest->rules(),$LoginRequest->messages());
if($validator->fails()){
return response()->json($validator->errors(), 422);
}
}
In order to display error messages in your API's, use response() method in your LoginRequest class, so you always return JSON. Something like this:
public function response(array $errors)
{
// Always return JSON.
return response()->json($errors, 422);
}
Now try to submit empty form, and you should be able to view the error message.

How to mock a Validation Rule in Laravel

I want to mock a custom Validation rule (e.g. App\Rules\SomeRule). But when I run my test, it gives an Mockery\Exception\InvalidCountException: Method...should be called
exactly 1 times but called 0 times.
I've read Laravel's documentation on Mocking, on custom Validation Rules, Service Containers, Service Providers and I cannot figure out why I'm not successfully mocking the rule.
I read this thread but I'm struggling to connect it with my problem which is, "How can I test that my app is using this Rule". Or is that something I cannot test?
Here's my Rule
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class SomeRule implements Rule
{
public function passes($attribute, $value)
{
// some logic, returns TRUE if valid.
}
public function message()
{
//
}
}
My controller
namespace App\Http\Controllers;
use App\Rules\SomeRule;
use Illuminate\Http\Request;
class LoanController extends Controller
{
public function store(Request $request)
{
$request->validate([
'email' => ['required', new SomeRule]
]);
// ...insert in database, return json.
}
}
My Test
namespace Tests\Feature;
use Mockery;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Rules\SomeRule;
class LoansTest extends TestCase
{
use RefreshDatabase;
public function tearDown(): void
{
parent::tearDown();
Mockery::close();
}
/** #test */
public function the_sad_path__when_email_is_invalid()
{
$rule = Mockery::mock(SomeRule::class)->shouldReceive('passes')->once();
$this->app->instance(SomeRule::class, $rule);
$response = $this->json('POST', '/api/loans', ['email' => 'whatevs#gmail.com']);
}
}
I played with the idea of registering SomeRule in the AppServiceProvider. But that still didn't do anything:
public function register()
{
$this->app->bind(SomeRule::class, function ($app) {
return new SomeRule();
});
}
Code in Github
you need to use like this
class LoanController extends Controller
{
public function store(Request $request)
{
$request->validate([
'email' => ['required', new SomeRule()]
]);
// ...insert in database, return json.
}
}

`Class not found` error even though class is defined as a modal

I have the following method in my controller:
public function store(Request $request){
$data = session()->get('dmca');
// return $data;
$notice = Notice::open($date);
$notice->useTemplate($request->input('template'));
$notice->save();
return Notice::first();
}
When the controller runs i get the following error:
Now i do have the following modal class:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Notice extends Model {
protected $fillable = [
'provider_id',
'infringing_title',
'infringing_link',
'original_link',
'original_description',
'template',
'content_removed'
];
public static function open(array $attributes) {
return new static($attributes);
}
public function useTemplate($template) {
$this->template = $template;
}
}
Now why am i getting this error in laravel class not found , even though i have this class defined ??
Just use use keyword at the top of your controller class.
<?php
namespace App\Http\Controllers;
use App\Notice; // <------------------ use here
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function store(Request $request)
{
$data = session()->get('dmca');
// return $data;
$notice = Notice::open($date);
$notice->useTemplate($request->input('template'));
$notice->save();
return Notice::first();
}
}
The use keyword helps php to recognize the class Notice within a certain namespace
Hope this helps!
Add this line to the top of a controller:
use App\Notice;
Or use full namespace:
$notice = \App\Notice::open($date);

Class App\Http\Controllers\Auth\Request does not exist. Laravel 5.3

I am using Laravel 5.3 My ForgotPasswordController looks like that:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Base\BaseController;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
class ForgotPasswordController extends BaseController
{
use SendsPasswordResetEmails;
public function __construct()
{
$this->middleware('guest');
}
public function showLinkRequestForm()
{
$title = $this->title;
$appName = $this->appName;
$action = $this->action;
return view('password.forgotPassword')->with(compact('title', 'appName', 'action'));
}
}
ResetPasswordController code :
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Base\BaseController;
use Illuminate\Foundation\Auth\ResetsPasswords;
class ResetPasswordController extends BaseController
{
use ResetsPasswords;
public function __construct()
{
$this->middleware('guest');
}
public function showResetForm(Request $request, $token = null)
{
return view('passwords.resetPassword')->with(
['token' => $token, 'email' => $request->email]
);
}
public function reset(Request $request)
{
$this->validate($request, [
'token' => 'required',
'password' => 'required|confirmed|min:6',
]);
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$this->resetPassword($user, $password);
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($response)
: $this->sendResetFailedResponse($request, $response);
}
}
My Admin Route :
Route::group(['namespace' => 'Auth'], function() {
Route::get('/forgotpassword/reset', 'ForgotPasswordController#showLinkRequestForm');
Route::post('/forgotpassword/email', 'ForgotPasswordController#sendResetLinkEmail');
Route::get('/password/reset/{token}', 'ResetPasswordController#showResetForm');
Route::post('/password/reset', 'ResetPasswordController#reset');
});
BaseController Code :
<?php
namespace App\Http\Controllers\Base;
use App\Http\Controllers\Controller;
class BaseController extends Controller
{
protected $appName = 'Stackoverflow';
protected $title = 'Welcome to Stackoverflow';
protected $action;
}
I can send the link to my email, but once I click the link/button.
It throws an error like above. Any idea ?
You are not using the required namespace, try to use the following in your controller:
use Illuminate\Http\Request;
You are getting the error due to the fact that your script tries to load the Request class from the current namespace :App\Http\Controllers\Auth
Request docs for Laravel 5.3

Class 'Validator' not found in Lumen

try to create validator manually in Lumen. The official documentation is written:
<?php
namespace App\Http\Controllers;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class PostController extends Controller
{
/**
* Store a new blog post.
*
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
}
I wrote
<?php
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController,
Validator;
class Welcome extends BaseController
{
public function index()
{
$validator = Validator::make(
['test' =>'TestValidation'],
['test' => 'required|unique:posts|max:255']
);
}
}
but Lumen returns fatal error:
Fatal error: Class 'Validator' not found in ...
I have tried to do like in Laravel 5:
use Illuminate\Support\Facades\Validator;
but then Lumen returns
Fatal error: Call to a member function make() on a non-object in
Somebody knows how to use the Validator class in Lumen? Thank you.
Validator is a facade. Facades aren't enabled by default in lumen.
If you would like to use the a facade, you should uncomment the
$app->withFacades();
call in your bootstrap/app.php file.
This is for Lumen version 5.3 (as shown in the docs):
use Illuminate\Http\Request;
$app->post('/user', function (Request $request) {
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users'
]);
// Store User...
});
https://lumen.laravel.com/docs/5.3/validation

Categories