Laravel error messages for extended custom validator class - laravel

Here is my validation service provider.
<?php namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Services\Validation\CustomValidation;
class ValidationServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* #return void
*/
public function register()
{
// We don't have to register anything here so we keep this empty!
}
/**
* Boot the service provider.
*/
public function boot()
{
// Need to override the default validator with our own validator
// We can do that by using the resolver function
$this->app->validator->resolver(function ($translator, $data, $rules, $messages) {
// This class will hold all our custom validations
return new CustomValidation($translator, $data, $rules, $messages);
});
}
}
Here is the custom validation class that extends Laravel validator class. I am confusing around where should I write my error messages for the custom rule. I could find any documentation for it.
<?php namespace App\Services\Validation;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Validator;
class CustomValidation extends Validator
{
/**
* $attribute Input name
* $value Input value
* $parameters Table, field1
*/
public function validateCustomRule($attribute, $value, $parameters)
{
// Logic to be written later
return false;
}
}

Have you tried adding them to the validation language file using the same convention? 'custom_rule' => 'Some message'

Related

target class interface is not instantiable while building

i am using design patterns repository and i wrote every thing coorect but i have an error returns
Target [App\Repository\categoryRepositoryInterface] is not instantiable while building [App\Http\Controllers\CategoryController]. i dont know why although i wrote every thing correct please help
here is my code
my config/app
App\Providers\RepositoryServiceProvider::class,
and my categorycontroller
<?php
namespace App\Http\Controllers;
use App\Repository\categoryRepositoryInterface;
use Illuminate\Http\Request;
class CategoryController extends Controller
{
private categoryRepositoryInterface $categoryRepository;
public function __construct(categoryRepositoryInterface $categoryRepository)
{
$this->categoryRepository = $categoryRepository;
}
and my repositoryinterface
<?php
namespace App\Repository;
use Illuminate\Http\Request;
interface categoryRepositoryInterface
{
public function createCategory(Request $request);
public function validation(Request $request);
}
and my category repository
<?php
namespace App\Repository;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class categoryRepository implements categoryRepositoryInterface{
public function validation(Request $request){
$validation = Validator::make($request->all(),[
'name' => 'required',
]);
if($validation->fails()){
return response()->json([
'status' => 400,
'errors' => $validation->errors(),
]);
}
}
public function createCategory(Request $request)
{
$category = new Category();
$category->name = $request->name;
$category->save();
}
}
and my servicerepositoryprovider
<?php
namespace App\Providers;
use App\Repository\CategoryRepository;
use App\Repository\CategoryRepositoryInterface;
use Illuminate\Support\ServiceProvider;
class RepositoryServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* #return void
*/
public function register()
{
$this->app->bind(CategoryRepositoryInterface::class, CategoryRepository::class);
}
/**
* Bootstrap services.
*
* #return void
*/
public function boot()
{
//
}
}
You have typos in your RepositoryServiceProvier
use App\Repository\categoryRepository; //First alphabet should be lower case
use App\Repository\categoryRepositoryInterface; //First alphabet should be lower case
use Illuminate\Support\ServiceProvider;
class RepositoryServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* #return void
*/
public function register()
{
//First alphabet should be lower case as per your class and interface names
$this->app->bind(categoryRepositoryInterface::class, categoryRepository::class);
}
/**
* Bootstrap services.
*
* #return void
*/
public function boot()
{
//
}
}
Would like to give you a piece of advice. When developing with Laravel it would be easier for you to follow Laravel's naming conventions - Laravel conventions overall. Following conventions will help you better understand examples on the internet as well.
Whatever you decide remember to follow them with consistency. In this particular case you are naming classes in camel case starting with small alphabet so when importing via use statements you need to stick to that.

Laravel: Issue with calling custom Facade

I'm using Laravel 8 and I'm creating a custom Facade, but I cannot recall it with LogActivity::log($payload) but only with LogActivityFacade::log($payload).
Cannot see where is my fault...
app\Helpers\LogActivityFacade.php
<?php
namespace App\Helpers;
use Illuminate\Support\Facades\Facade;
class LogActivityFacade extends Facade
{
protected static function getFacadeAccessor()
{
return 'logactivity';
}
}
app\Helpers\LogActivityHelper.php
<?php
namespace App\Helpers;
use App\Repositories\LogActivityRepository;
class LogActivityHelper
{
public function log($payload)
{
$repository = new LogActivityRepository();
$repository->store($payload);
}
}
app\Providers\LogActivityServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\App;
use App\Helpers\LogActivityHelper;
use Illuminate\Support\ServiceProvider;
class LogActivityServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* #return void
*/
public function register()
{
$this->app->bind('logactivity', function() {
return new LogActivityHelper();
});
}
/**
* Bootstrap services.
*
* #return void
*/
public function boot()
{
//
}
}
config/app.php
In providers array
[...]
App\Providers\LogActivityServiceProvider::class,
In alias array
'LogActivity' => App\Helpers\LogActivityFacade::class,
I tried also composer dump-autoload and php artisan config:clear, but I can access to the Facade (and it works...) only with LogActivityFacade::log() instead of LogActivity.
This is the expected behavior. Laravel doesn't create new classes for you it just proxies methods from the service class in the facade using the __call magic method. If you take a peek at, for example, the Auth or Route facade in the vendor directory you will see that they are named Auth and Route respectively not AuthFacade and RouteFacade. So just name your facade LogActivity. If you need to differentiate it from the service class you can use namespacing or just postfix the service class name with something as you have already done.
You can do this for easy access to the facades
namespace App\Facade;
use Illuminate\Support\Facades\Facade;
abstract class BaseFacade extends Facade
{
/**
* #return string
*/
public static function getFacadeAccessor()
{
return static::class ;
}
/**
* #param $class
*/
static function shouldProxyTo($class)
{
app()->singleton(self::getFacadeAccessor(),$class);
}
}
extend other facades
namespace App\Facade\Plugins;
use App\Facade\BaseFacade;
/**
* #method static convertPersianNumberToEnglish($number)
* #method static bool checkDataIsTrue(array $results = [])
* #method static string|null removeFileTypeName(string $string = null)
*/
class GlobalPluginsFacade extends BaseFacade
{
}
register in services provider
public function boot()
{
// global facades
GlobalPluginsFacade::shouldProxyTo(GlobalPluginsRepo::class);
}
And easy to use.
GlobalPluginsFacade::getFunction();

Laravel class not found for mail

I'm trying to generate a notification email to the webmaster when there's a new registration on the site I'm building.
I have a mail class called SignedUp at App\Mail\SignedUp.php.
In the Illuminate/Foundation/Auth/RegistersUser file, I have the following:
namespace Illuminate\Foundation\Auth;
use App\Organization;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Auth\Events\Registered;
use App\Mail\SignedUp;
trait RegistersUsers
{
use RedirectsUsers;
/**
* Show the application registration form.
*
* #return \Illuminate\Http\Response
*/
public function showRegistrationForm()
{
$organizations = Organization::all();
return view('auth.register', compact('organizations'));
}
/**
* Handle a registration request for the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
Mail::to('example#example.com')->send(new SignedUp($user));
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
When I register a new user, I get this message:
Class 'Illuminate\Foundation\Auth\Mail' not found
if I change use App\Mail\SignedUp; to use App\Mail;, the error is still: Class 'Illuminate\Foundation\Auth\Mail' not found
use Mail; gives me Illuminate\Foundation\Auth\SignedUp' not found
use App\Mail\SignedUp; gives me Class 'Illuminate\Foundation\Auth\Mail' not found
Not attempting to import the class at all, and instead changing my statement to: \Mail::to('example#example.com')->send(new SignedUp($user));, I get Class 'Illuminate\Foundation\Auth\SignedUp' not found
A cannot figure out how to get it to find my mail class.
I'm just guessing and shooting in the dark - can anyone see what I'm doing wrong?
Here is my mail class file:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class SignedUp extends Mailable
{
use Queueable, SerializesModels;
public $url = 'https://av-cuauhtemoc.org/users';
public $user;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('example#example.com')->view('emails.new-registration');
}
}
I finally stumbled upon the answer.
I also needed to import the use Illuminate\Support\Facades\Mail; class.
So this works:
use App\Mail\Signedup;
use Illuminate\Support\Facades\Mail;
first of all you shouldn't change Illuminate/Foundation/Auth/RegistersUser file, instead you have to overwrite this method in your RegisterController:
use App\Mail\SignedUp;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Mail;
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
Mail::to('example#example.com')->send(new SignedUp($user));
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}

Setup Third party package into custom service provider

I'm trying to apply a sort of "repository-pattern" to a custom service.
What I'd like to do is to actually bind this library to my custom service provider to create an abstraction layer and, eventually, switch that library with another one in the future.
I'm trying to move the 'providers' and 'aliases' references from config/app.php to my service provider, but I get a Class 'GoogleMaps' not found error.
I've added App\Providers\GeoServiceProvider::class to config/app.php providers array and this is my relevant code:
GeoServiceProvider.php(my custom service provider)
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class GeoServiceProvider extends ServiceProvider
{
/** * Register services.
*
* #return void
*/
public function register()
{
$this->app->bind(\App\Interfaces\GeoInterface::class, \App\Services\GoogleGeoService::class);
$this->app->alias(\GoogleMaps\Facade\GoogleMapsFacade::class, 'GoogleMaps');
}
/**
* Bootstrap services.
*
* #return void
*/
public function boot()
{
}
}
GeoInterface.phpinterface defining standard methods
<?php
namespace App\Interfaces;
interface GeoInterface
{
public function geoCode();
}
GoogleGeoService.php(The actual library implementation)
<?php
namespace App\Services;
use App\Interfaces\GeoInterface;
class GoogleGeoService implements GeoInterface
{
public function geoCode()
{
$response = \GoogleMaps::load( 'geocoding' ) <--- HERE IS WHERE I GET THE ERROR
->setParamByKey( 'latlng', "45.41760620,11.90208370")
->setEndpoint( 'json' )
->get();
$response = json_decode($response, true);
return $response;
}
}
TestController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Interfaces\GeoInterface;
class TestController extends Controller
{
protected $geoService;
public function __construct(GeoInterface $geoService) {
$this->geoService = $geoService;
}
public function index() {
return $this->geoService->geoCode();
}
}
Thank you,
Alex

Laravel 5.3 Call to a member function groupBy() on null

I'm getting the following error:
FatalErrorException in EloquentVehicle.php line 30: Call to a member
function groupBy() on null
I have the following code:
<?php
namespace App\Project\Frontend\Repo\Vehicle;
use Illuminate\Database\Eloquent\Model;
class EloquentVehicle implements VehicleInterface
{
protected $vehicle;
/**
* EloquentVehicle constructor.
*
* #param Model $vehicle
*/
public function __construct(
Model $vehicle
)
{
$this->$vehicle = $vehicle;
}
/**
* Fetch unique makes
*
* #return mixed
*/
public function fetchMakes()
{
return $this->vehicle->groupBy(array('make'))
->orderBy('make', 'asc')
->get();
}
}
I've checked Illuminate\Database\Eloquent\Model for the method which is obviously not there, but I don't know what I should be adding to my class so that I can use the groupBy method. The laravel docs say the method exists.
UPDATE: Apparently I can't typehint an abstract class. I don't know how else I should be going about using Eloquent to retrieve records. If it helps, below is the code I have for registering the classes to the service container
<?php
namespace App\Providers;
use App\Vehicle;
use App\Project\Frontend\Repo\Vehicle\EloquentVehicle;
use Illuminate\Support\ServiceProvider;
class RepoServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
$this->app->bind('App\Project\Frontend\Repo\Vehicle\VehicleInterface', function($app)
{
return new EloquentVehicle(
new Vehicle
);
});
}
}
I just found my mistake and quite literally lay my face in my palms.
This
$this->$vehicle = $vehicle;
should be this
$this->vehicle = $vehicle;

Resources