How to solve Class 'App\Http\Requests\Web\WebRequest' not found - laravel-5

I create a request in App\Http\Requests\Web in which it shows me the error.
Class 'App\Http\Requests\Web\WebRequest' not found
Here is the code of my Request CreateBucket.php:
<?php
namespace App\Http\Requests\Web;
class CreateBucket extends WebRequest
{
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'bucket_name' => 'required|string|string|max:30',
'bucket_type' => 'required|string|string|max:30',
'bucket_image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg',
];
}
}
And Here is my code of Bucket Controller:
<?php
namespace App\Http\Controllers\Web;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\Web\CreateBucket;
use App\Bucket;
class BucketController extends Controller
{
public function index(Request $request)
{
$buckets = Bucket::orderBy('id','ASC')->paginate(10);
return view('buckets.index',compact('buckets',$buckets))
->with('i',($request->input('page',1) - 1) * 10);
}
public function create()
{
return view('buckets.create');
}
public function store(CreateBucket $request)
{
if($request->hasFile('bucket_image')) {
$bucket_image = $request->file('bucket_image');
$bucket_image_name = time().'.'.$bucket_image->getClientOriginalExtension();
$path = public_path('Storage/BucketImages');
$bucket_image->move($path, $bucket_image_name);
$bucket_image = 'Storage/BucketImages/'.$bucket_image_name;
} else {
$bucket_image = NULL;
}
$category = Category::create([
'bucket_name' => $request->input('bucket_name'),
'bucket_image'=> $bucket_image,
'bucket_type' => $request->input('bucket_type'),
]);
return redirect()->route('buckets.index')
->with('success','Bucket created successfully');
}
Please Help me to resolve this error. Thanks.

My WebRequest.php is missing in Requests folder that why he gave me this Error.
Here is the WebRequest.php file I created and my issue is resolve.
<?php
namespace App\Http\Requests\Web;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
class WebRequest 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 [
//
];
}
}

Related

Laravel Http client before request send add headers

I'm using Http client for making outgoing HTTP requests. I've used it many places in the project.Now project has new requirement that I have to add a new header to every outgoing
requests. I can do this by adding it to every places. But I want to know , is there any kind of trigger or event which can give me ability to modify the headers just before the request send. There is an event Illuminate\Http\Client\Events\RequestSending which is only useful for inspecting the request.
This is possible to achieve without the need of a package. You can simple do something like this in a service provider:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Http\Client\Factory as Http;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
$this->app->extend(Http::class, function ($service, $app) {
return $service->withOptions(['foo' => 'bar']);
});
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
//
}
}
Yes, this is possible with a fantastic package here. After installing the package you just set the default headers like,
Http::withDefaultOptions([
'headers' => [
'X-Bar-Header' => 'bar'
],
]);
But I was unfortunate, the package was not installed with my laravel 9-dev. So I had to extract the code for me. First, create a Factory class in your app\HttpClient directory,
<?php
namespace App\HttpClient;
use Illuminate\Http\Client\Factory as BaseFactory;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Arr;
class Factory extends BaseFactory
{
protected $ignoreDefaultOptions = false;
protected $defaultOptions = [];
public function ignoreDefaultOptions()
{
$this->ignoreDefaultOptions = true;
return $this;
}
public function withoutDefaultOptions($keys = null)
{
if ($keys === null) {
return $this->ignoreDefaultOptions();
}
if (func_num_args() > 1) {
$keys = func_get_args();
}
$this->defaultOptions = with($this->defaultOptions, function ($options) use ($keys) {
foreach (Arr::wrap($keys) as $key) {
Arr::forget($options, $key);
}
return $options;
});
return $this;
}
public function withDefaultOptions(array $options)
{
$this->defaultOptions = array_merge_recursive($this->defaultOptions, $options);
return $this;
}
public function __call($method, $parameters)
{
if (static::hasMacro($method)) {
return $this->macroCall($method, $parameters);
}
if ($this->defaultOptions && ! $this->ignoreDefaultOptions) {
return tap(new PendingRequest($this), function ($request) {
$request->withOptions($this->defaultOptions)
->stub($this->stubCallbacks);
})->{$method}(...$parameters);
}
return parent::__call($method, $parameters);
}
}
Then, create a HttpServiceProver,
php artisan make:provider HttpServiceProvider
And put the following code there,
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Http\Client\Factory as BaseFactory;
use App\HttpClient\Factory;
class HttpServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* #return void
*/
public function register()
{
$this->app->bind(
BaseFactory::class,
function ($app) {
return new Factory($app->make(Dispatcher::class));
}
);
}
/**
* Bootstrap services.
*
* #return void
*/
public function boot()
{
//
}
}
Now, register the newly created service provider in AppServiceProvider.php
public function register()
{
//...
app()->register(HttpServiceProvider::class);
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
//....
Http::withDefaultOptions([
'headers' => [
'X-Bar-Header' => 'bar'
],
]);
}
There are other options in this package. Please check it the package link for details.

Expected status code 200 but received 302

i'm trying to perform a test to check if
1 - the user is authenticated
2 - has permission to view the requested page
every time i run the test i get this error
Expected status code 200 but received 302.
namespace Tests\Feature\Category;
class CategoryTest extends TestCase
{
use RefreshDatabase;
/** #test */
public function it_can_see_all_categories()
{
$user = $this->signedIn();
$permission = Permission::create(['group' => 'categories' , 'name' => 'view categories' , 'label' => 'view categories']);
$role = Role::find($user->role_id);
$role->givePermissionTo($permission);
$response = $this->get('/categories');
$response->assertStatus(200 , $response->getStatusCode());
}
}
My Controller
<?php
namespace App\Http\Controllers\Category;
class CategoriesController extends Controller
{
protected $categRepo;
/**
* Initializing Categories Repository
*/
public function __construct(CategoryRepository $categRepo)
{
$this->categRepo = $categRepo;
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(ManageCategoryRequest $request)
{
$categories = $this->categRepo->getPaginated(25);
return view('categories.index' , compact('categories'));
}
}
And here is My Request For Request Authorization
<?php
class ManageCategoryRequest extends FormRequest
{
public function authorize()
{
return $this->user()->can('view categories');
}
}
Probably not signed in! looking at signedIn

How to extend controller in Codeigniter 4?

How can I create my own core controller in codeigniter 4 like codeigniter 3?
When you say "core" controller I understand you to mean a "base" controller which in CI v3 is often named MY_Controller. If that is what you are asking for it's actually much easier in v4 because of namespaces and the autoloader. Also, there is no need for the trickery of using a prefix like MY_.
Here's just how easy it is. The "base" controller...
File: /application/Controllers/Base.php
<?php namespace App\Controllers;
class Base extends \CodeIgniter\Controller
{
//your code here
}
Then extend the above to create any other controller
File: /application/Controllers/Home.php
<?php namespace App\Controllers;
class Home extends \App\Controllers\Base
{
// Your code here
}
The Home controller will inherit all the properties and methods you define in Base.
You do not need to create another core controller, there is already a core controller provided, which is BaseController.
You need to just extend it to your choice
Try this
<?php namespace App\Core;
use CodeIgniter\Controller;
class Home extends Controller
{
}
see my codes
<?php
namespace Modules\Shared\Controllers;
/**
* Class BaseController
*
* BaseController provides a convenient place for loading components
* and performing functions that are needed by all your controllers.
* Extend this class in any new controllers:
* class Home extends BaseController
*
* For security be sure to declare any new methods as protected or private.
*
* #package CodeIgniter
*/
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;
use Modules\Auth\Config\Services;
use Myth\Auth\AuthTrait;
use Psr\Log\LoggerInterface;
use Modules\Shared\Interfaces\UrlQueryParamInterface;
use Modules\Shared\Libraries\UrlQueryParam;
class ApiController extends ResourceController
{
use AuthTrait;
protected $format = "";
public object $userObject;
public UrlQueryParamInterface $urlQueryParam;
/**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* #var array
*/
protected $helpers = [
'cookie',
'url',
'from',
'filesystem',
'text',
'shared'
];
/**
* Constructor.
*
* #param RequestInterface $request
* #param ResponseInterface $response
* #param LoggerInterface $logger
*/
/**
* #var string
* Holds the session instance
*/
protected $session;
public function __construct()
{
$this->userObject = (object)[];
}
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
$this->urlQueryParam = new UrlQueryParam($request);
$requestWithUser = Services::requestWithUser();
$this->userObject = $requestWithUser->getUser();
}
}
<?php
namespace Modules\Common\Controllers;
use Modules\Common\Config\Services;
use Modules\Common\Entities\AdvertisementEntity;
use CodeIgniter\HTTP\ResponseInterface;
use Modules\Shared\Controllers\ApiController;
class Advertisement extends ApiController
{
/**
* index function
* #method : GET
*/
public function index()
{
$advertisementEntity = new AdvertisementEntity();
$this->urlQueryParam->dataMap($advertisementEntity->getDataMap());
$advertisementService = Services::advertisementService();
$findAllData = $advertisementService->index($this->urlQueryParam);
return $this->respond([
'data' => $findAllData['data'],
'pager' => $findAllData['pager']
], ResponseInterface::HTTP_OK, lang('Shared.api.receive'));
}
/**
* show function
* #method : GET with params ID
*/
public function show($id = null)
{
$advertisementService = Services::advertisementService();
$findOneData = $advertisementService->show($id);
return $this->respond([
'data' => $findOneData['data'],
'pager' => $findOneData['pager']
], ResponseInterface::HTTP_OK, lang('Shared.api.receive'));
}
/**
* create function
* #method : POST
*/
public function create()
{
$rules = [
'name' => 'required|min_length[3]|max_length[255]',
'link' => 'required',
];
if (!$this->validate($rules)) {
return $this->respond([
'error' => $this->validator->getErrors(),
], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Shared.api.validation'));
};
$advertisementEntity = new AdvertisementEntity((array)$this->request->getVar());
$advertisementEntity->enableStatus()->createdAt();
$advertisementService = Services::advertisementService();
$advertisementService->create($advertisementEntity);
return $this->respond([
'insertId' => $advertisementService->getInsertID()
], ResponseInterface::HTTP_CREATED, lang('Shared.api.save'));
}
/**
* update function
* #method : PUT or PATCH
*/
public function update($id = null)
{
if ($this->request) {
//get request from Vue Js
$json = $this->request->getJSON();
if (!isset($id)) {
$id = $json->id;
}
$rules = [
'name' => 'required|min_length[3]|max_length[255]',
'link' => 'required',
];
if (!$this->validate($rules)) {
return $this->respond([
'error' => $this->validator->getErrors(),
], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Shared.api.validation'));
}
$advertisementEntity = new AdvertisementEntity((array)$this->request->getVar());
$advertisementEntity->updatedAt();
$advertisementService = Services::advertisementService();
$advertisementService->update($id, $advertisementEntity);
}
return $this->respond([
], ResponseInterface::HTTP_OK, lang('Shared.api.update'));
}
/**
* edit function
* #method : DELETE with params ID
*/
public function delete($id = null)
{
$advertisementService = Services::advertisementService();
$advertisementService->delete($id);
return $this->respond([
], ResponseInterface::HTTP_OK, lang('Shared.api.remove'));
}
}

redirect to controller instead of view when validation failed in laravel 5.1

in my controller :
public function getData(\App\Http\Requests\NewNameRequest $request)
{
return 'Your name is : '.$request->input('myName');
}
in my NewNameRequest.php class
namespace App\Http\Requests;
use App\Http\Requests\Request;
class NewNameRequest extends Request
{
/**
* 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 [
'myName'=>'required|min:3|max:10'
];
}
}
what i want is ...
if (NewNameRequest is Failed)
{
do this...
}
else
{
proceed ahead in controller
}
thanks in time ahead

Laravel 5 Custom Validator resolver not found

Hi Guys I would like to register my new CustomValidator class. This contains some validation for a mobile number I created this class
<?php
// This class is located in App\Validator
use Illuminate\Validation\Validator;
class CustomValidator extends Validator {
public function validateIsKyc($attribute, $value, $parameters)
{
return $value == 'is_kyc';
}
}
Now in my AppServiceProvider here's my code for loading that class
<?php
namespace App\Providers;
use Illuminate\Validation\Validator;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Validator::resolver(function($translator, $data, $rules, $messages)
{
return new CustomValidator($translator, $data, $rules, $messages);
});
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}
And on my request I tried using the custom validation like so
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class CreateRegistrationRequest extends Request
{
/**
* 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 [
'phone_no' => "required|isKyc",
];
}
}
But I get this error
FatalErrorException in AppServiceProvider.php line 23: Call to undefined method Illuminate\Validation\Validator::resolver()
Don't know what went wrong any idea please...
In the file App\Validator\CustomValidator.php you need to add at the beginning
<?php namespace App\Validator;
In the file AppServiceProvider.php you need to add at the beginning
use App\Validator\CustomValidator;
and also replace this
use Illuminate\Validation\Validator;
with this
use Validator;
My bad guys,
I already know the solution, i doing something wrong, i wasn't aware im putting my code into the register function instead to boot() function.
From
public function register()
{
Validator::resolver(function($translator, $data, $rules, $messages)
{
return new CustomValidator($translator, $data, $rules, $messages);
});
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
}
to this,
public function register()
{
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Validator::resolver(function($translator, $data, $rules, $messages)
{
return new CustomValidator($translator, $data, $rules, $messages);
});
}
now i can manage my customvalidators to one class only. :)
GGWP Laravel!

Resources