In my Laravel-8 application, I am trying to bind Repository to an Interface
I have this code:
App\Providers\RepositoryServiceProvider:
class RepositoryServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind(
'App\Interfaces\Auth\AuthInterface',
'App\Repositories\Auth\AuthRepository'
);
}
}
config\app:
App\Providers\RepositoryServiceProvider::class,
Then the interface looks like this:
namespace App\Interfaces\Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
interface AuthInterface
{
public function register(Request $request);
}
Repository Implementation:
namespace App\Repositories\Auth;
use App\Interfaces\Auth\AuthInterface;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use App\Traits\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class AuthRepository implements AuthInterface
{
use ApiResponse;
public function register(DriverRequest $request)
{
DB::beginTransaction();
try {
$newUser = User::create([
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'email' => preg_replace('/\s+/', '', strtolower($request->email)),
'password' => bcrypt($request->password)
]);
DB::commit();
return $this->success('Signup Successfully Done, please check your email to activate account', $newUser);
} catch(\Exception $e) {
DB::rollback();
Log::error($e);
return $this->error($e->getMessage(), $e->getCode());
}
}
}
Controller
use App\Interfaces\Auth\AuthInterface;
class AuthController extends Controller
{
protected $authInterface;
public function __construct(AuthInterface $auth)
{
$this->authInterface = $auth;
}
public function register(Request $request)
{
return $this->authInterface->register($request);
}
}
When I did php artisan route:list, I got this error:
Illuminate\Contracts\Container\BindingResolutionException
Target [App\Interfaces\Auth\AuthInterface] is not instantiable while building [App\Http\Controllers\Api\V1\Auth\AuthController].
at C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Container\Container.php:1049
1045▕ } else {
1046▕ $message = "Target [$concrete] is not instantiable.";
1047▕ }
1048▕
➜ 1049▕ throw new BindingResolutionException($message);
1050▕ }
1051▕
1052▕ /**
1053▕ * Throw an exception for an unresolvable primitive.
1 C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Container\Container.php:842
Illuminate\Container\Container::notInstantiable("App\Interfaces\Auth\AuthInterface")
2 C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Container\Container.php:714
Illuminate\Container\Container::build("App\Interfaces\Auth\AuthInterface")
How do I get it resolved?
Thanks
It might be from your namespace, I had the same issue...it came from my namespace
Related
I need to modify /vendor/laravel/fortify/src/Contracts/CreatesNewUsers.php interface
and to add 1 more bool parameter, as using CreateNewUser in different places of the app
validations rules are different, say in some places password is not filled on user creation, but must be separate function.
So I copied file /project/resources/fortify/CreatesNewUsers.php with content :
<?php
namespace Laravel\Fortify\Contracts;
interface CreatesNewUsers
{
public function create(array $input, bool $makeValidation);
}
and in app/Actions/Fortify/CreateNewUser.php I modified :
<?php
namespace App\Actions\Fortify;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
//use Laravel\Fortify\Contracts\CreatesNewUsers;
use Resources\Fortify\CreatesNewUsers; // Reference to my interface
use Laravel\Jetstream\Jetstream;
class CreateNewUser implements CreatesNewUsers
{
use PasswordValidationRules;
public function create(array $input, bool $makeValidation)
{
...
But trying to use this class I got error
Interface "Resources\Fortify\CreatesNewUsers" not found
Which is the valid way ?
Thanks!
I moved interface at file app/Actions/Fortify/CreatesNewUsers.php :
<?php
namespace App\Actions\Fortify;
interface CreatesNewUsers
{
public function create(array $input, bool $make_validation, array $hasPermissions);
}
and modified app/Actions/Fortify/CreateNewUser.php :
<?php
namespace App\Actions\Fortify;
use App\Models\User;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use DB;
use App\Actions\Fortify\CreatesNewUsers;
use Laravel\Jetstream\Jetstream;
use Spatie\Permission\Models\Permission;
class CreateNewUser implements CreatesNewUsers
{
use PasswordValidationRules;
/**
* Validate and create a newly registered user.
*
* #param array $input
*
* #return \App\Models\User
*/
public function create(array $input, bool $make_validation, array $hasPermissions)
{
if ($make_validation) {
$userValidationRulesArray = User::getUserValidationRulesArray(null, '', []);
if (\App::runningInConsole()) {
unset($userValidationRulesArray['password_2']);
}
$validator = Validator::make($input, $userValidationRulesArray);//->validate();
if ($validator->fails()) {
$errorMsg = $validator->getMessageBag();
if (\App::runningInConsole()) {
echo '::$errorMsg::' . print_r($errorMsg, true) . '</pre>';
}
return $errorMsg;
}
} // if($make_validation) {
$newUserData = [
'name' => $input['name'],
'email' => $input['email'],
'account_type' => $input['account_type'],
'phone' => $input['phone'],
'website' => $input['website'],
'notes' => $input['notes'],
'first_name' => $input['first_name'],
'last_name' => $input['last_name'],
];
if (isset($input['password'])) {
$newUserData['password'] = Hash::make($input['password']);
}
if (isset($input['status'])) {
$newUserData['status'] = $input['status'];
}
if (isset($input['activated_at'])) {
$newUserData['activated_at'] = $input['activated_at'];
}
if (isset($input['avatar'])) {
$newUserData['avatar'] = $input['avatar'];
}
try {
DB::beginTransaction();
$newUser = User::create($newUserData);
foreach ($hasPermissions as $nextHasPermission) {
$appAdminPermission = Permission::findByName($nextHasPermission);
if ($appAdminPermission) {
$newUser->givePermissionTo($appAdminPermission);
}
}
DB::commit();
return $newUser;
} catch (QueryException $e) {
DB::rollBack();
if (\App::runningInConsole()) {
echo '::$e->getMessage()::' . print_r($e->getMessage(), true) . '</pre>';
}
}
return false;
}
}
It allows me to use CreateNewUser from different parts of app, like seeders, adminarea, user registration
with different behaviour. For me it seems good way of using fortify and CreateNewUser...
I don't understand this mistake, can someone help me?
I am taking a course on ApiRestfull and the code works for the teacher but I can't get it to work for me
I am using laravel 5.8*
The error he shows me is this: Error:
Argument 1 passed to App\Http\Controllers\ApiController::showAll() must be an instance of Illuminate\Database\Eloquent\Collection, instance of Illuminate\Support\Collection given, called in C:\laragon\www\udemy-apirestfull\app\Http\Controllers\Buyer\BuyerProductController.php on line 23
BuyerProductController.php:
<?php
namespace App\Http\Controllers\Buyer;
use App\Buyer;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;
class BuyerProductController extends ApiController
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Buyer $buyer)
{
$products = $buyer->transactions()->with('product')
->get()
->pluck('product');
return $this->showAll($products);
}
}
ApiController:
<?php
namespace App\Http\Controllers;
use App\Traits\ApiResponser;
use Illuminate\Http\Request;
class ApiController extends Controller
{
use ApiResponser;
}
ApiResponser:
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;
trait ApiResponser
{
private function successResponse($data, $code)
{
return response()->json($data, $code);
}
protected function errorResponse($message, $code)
{
return response()->json(['error' => $message, 'code' => $code], $code);
}
protected function showAll(Collection $collection, $code = 200)
{
return $this->successResponse(['data' => $collection], $code);
}
protected function showOne(Model $instance, $code = 200)
{
return $this->successResponse(['data' => $instance], $code);
}
}
Buyer model:
<?php
namespace App;
use App\Transaction;
use App\Scopes\BuyerScope;
class Buyer extends User
{
protected static function boot()
{
parent::boot();
static::addGlobalScope(new BuyerScope);
}
public function transactions()
{
return $this->hasMany(Transaction::class);
}
}
Product Model:
<?php
namespace App;
use App\Seller;
use App\Category;
use App\Transaction;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
use SoftDeletes;
const PRODUCTO_DISPONIBLE = 'disponible';
const PRODUCTO_NO_DISPONIBLE = 'no disponible';
protected $dates = ['deleted_at'];
protected $fillable = [
'name',
'description',
'quantity',
'status',
'image',
'seller_id',
];
public function estaDisponible()
{
return $this->status == Product::PRODUCTO_DISPONIBLE;
}
public function seller()
{
return $this->belongsTo(Seller::class);
}
public function transactions()
{
return $this->hasMany(Transaction::class);
}
public function categories()
{
return $this->belongsToMany(Category::class);
}
}
Transaction Model:
<?php
namespace App;
use App\Buyer;
use App\Product;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Transaction extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = [
'quantity',
'buyer_id',
'product_id',
];
public function buyer()
{
return $this->belongsTo(Buyer::class);
}
public function product()
{
return $this->belongsTo(Product::class);
}
}
Illuminate\Database\Eloquent\Collection extends Illuminate\Support\Collection
So if not mandatory, you can change the signature of showAll method to accept Illuminate\Support\Collection as a parameter
There will be no error if the parameter supplied will be an instance of Illuminate\Database\Eloquent\Collection
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection; //Changed here
trait ApiResponser
{
private function successResponse($data, $code)
{
return response()->json($data, $code);
}
protected function errorResponse($message, $code)
{
return response()->json(['error' => $message, 'code' => $code], $code);
}
protected function showAll(Collection $collection, $code = 200)
{
return $this->successResponse(['data' => $collection], $code);
}
protected function showOne(Model $instance, $code = 200)
{
return $this->successResponse(['data' => $instance], $code);
}
}
when trying to get data and returns it via transformers got an error Class 'App\\Api\\V1\\Controllers\\Auth\\ApiController' not found. Using ApiController to extends.I put APIcontroller to App\\Api\\V1\\Controllers\\Front folder.
LoginController Code and extends it to ApiController:
<?php
namespace App\Api\V1\Controllers\Auth;
use Auth;
use Carbon\Carbon;
use Tymon\JWTAuth\JWTAuth;
use App\Http\Controllers\Controller;
use App\Api\V1\Requests\LoginRequest;
use Tymon\JWTAuth\Exceptions\JWTException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use App\User;
use App\UserDeviceData;
use Illuminate\Http\Request;
use App\Transformers\UserTransformer;
class LoginController extends ApiController // extends to API controller
{
public function login(LoginRequest $request, JWTAuth $JWTAuth)
{
$credentials = $request->only(['email', 'password']);
try {
$token = Auth::guard()->attempt($credentials);
if(!$token) {
return response()->json([
'message' => "Email and password do not match",
'status_code' => 403,
]);
}
$user = Auth::user();
$user->last_login = Carbon::now();
$user->save();
$user = Auth::user();
$user->UserDeviceData()->firstOrCreate([
'device_id' => $request->device_id
]);
} catch (JWTException $e) {
return response()->json([
'message' => "Internal server error",
'status_code' => 500,
]);
}
return $this->response->collection($user, new UserTransformer);
}
}
Api controller code : and set namespace App\Api\V1\Controllers\Front;
<?php
namespace App\Api\V1\Controllers\Front;
use App\Support\Response;
use App\Support\Parameters;
abstract class ApiController extends Controller
{
protected $response;
protected $parameters;
public function __construct(Response $response, Parameters $parameters)
{
$this->response = $response;
$this->parameters = $parameters;
}
}
What is the problem in my code?
As ApiController and LoginController are using a different namespace, you need to use your ApiController in LoginController.
use App\Api\V1\Controllers\Front\ApiController;
You also forgot to use Controller in ApiController:
use App\Http\Controllers\Controller;
I am trying to catch in Laravel 5.5 the eloquent.created event when a Post model is created, but for any reason it does not work. It looks like the event/listener mapping that is defined inside the EventServiceProvider.php does not work. My setup is as follows.
EventServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
protected $listen = [
'App\Events\PostWasPublished' => [
'App\Listeners\NotifyBlogSubscribers',
]
];
public function boot()
{
parent::boot();
//
}
}
NotifyBlogSubscribers.php listener
<?php
namespace App\Listeners;
use App\Events\PostWasPublished;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class NotifyBlogSubscribers
{
public function __construct()
{
//
}
public function handle(PostWasPublished $event)
{
dd('Inside NotifyBlogSubscribers');
}
}
PostWasPublished.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class PostWasPublished
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct()
{
dd('Inside PostWasPublished');
}
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
Post.php
<?php
namespace App\Models;
use App\Events\PostWasPublished;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
protected $events = [
'created' => PostWasPublished::class,
];
protected $fillable = ['user_id', 'title', 'body'];
public function comments() {
return $this->hasMany(Comment::class);
}
public function addComment($body) {
Comment::create([
'body' => $body,
'post_id' => $this->id
]);
}
public function user() {
return $this->belongsTo('App\User');
}
public function scopeFilter($query, $filters) {
if (array_key_exists('month', $filters)) {
$month = $filters['month'];
$query->whereMonth('created_at', Carbon::parse($month)->month);
}
if (array_key_exists('year', $filters)) {
$year = $filters['year'];
$query->whereYear('created_at', $year);
}
}
public static function archives() {
return static::selectRaw('year(created_at) as year, monthname(created_at) as month, count(*) published')
->groupBy('year', 'month')
->orderByRaw('min(created_at) desc')
->get()
->toArray();
}
public function tags() {
return $this->belongsToMany(Tag::class);
}
}
How do I test?
My first approach is to use tinker in the following way:
>>> App\Models\Post::create(['user_id' => '1', 'title' => 'some title', 'body' => 'lorem ipsum'])
=> App\Models\Post {#732
user_id: "1",
title: "some title",
body: "lorem ipsum",
updated_at: "2017-08-07 05:06:32",
created_at: "2017-08-07 05:06:32",
id: 62,
}
Also, when I create a post in the front-end it does not run into the dd() methods.
Also composer dump-autoload, php artisan clear-compiled or php artisan optimize did not do the trick. Any idea what I am doing wrong?
In Laravel 5.5 you will need to define a $dispatchesEvents property instead of a $events property. ($events was used in older Laravel versions).
Undefined property: Illuminate\Validation\Validator::$errors in laravel
here is my controller file how to solve it i think here problem is any namespace where is it i do not know please guide me
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Route;
use Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Http\Request;
use App\models\Designation;
use Validator;
use Illuminate\Support\Facades\Response;
class Cdesigination extends Controller
{
public $flight;
public function __construct(){
$this->flight = new Designation;
}
public function index()
{
return view('designation');
}
public function techer(Request $request) {
$Validator =Validator::make(array(
'name'=>Input::get('name'),
'detail'=>Input::get('detail')
),array(
'name' => 'required',
'detail' => 'required'
));
if ($Validator->fails()) {
return Response::json([
'success'=>false,
'error' =>$Validator->errors->toArray()
]);
}
else{
$this->flight->name = $request->name;
$this->flight->detail = $request->detail;
$this->flight->save();
return Response::json([
'success'=>true]);
}
}
$Validator->errors()->toArray()
Errors() is function, so the braces are important