Laravel : Extends Controller not found - laravel

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;

Related

Temporary identifier passed back by server does not match laravel socialite

I am facing an issue when trying to login and register a user using Twitter. Google is working except for Twitter. I cant seem to figure it out.
Temporary identifier passed back by server does not match that of stored temporary credentials. Potential man-in-the-middle.
<?php
namespace App\Http\Controllers;
use Exception;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
class TwitterController extends Controller
{
protected $redirectTo = '/home';
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
public function handleProviderCallback($provider)
{
$user = Socialite::driver($provider)->user();
$authUser = $this->findOrCreateUser($user, $provider);
Auth::login($authUser, true);
return redirect($this->redirectTo);
}
public function findOrCreateUser($user, $provider)
{
$authUser = User::where('provider_id', $user->id)->first();
if ($authUser) {
return $authUser;
}
return User::create([
'name' => $user->getName(),
'username' => $user->getName(),
'email' => $user->getEmail(),
'provider' => $provider,
'provider_id' => $user->getId()
]);
}
}

Laravel - Target [App\Interfaces\Auth\AuthInterface] is not instantiable while building

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

Laravel session is lost or not created on redirect

We are trying to setup the Facebook social connect on our Laravel application, but it seems like we have an issue on session creation.
Here is the code for the Controller :
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Laravel\Socialite\Facades\Socialite;
use App\Services\SocialAuthService;
class SocialAuthController extends Controller
{
public function redirect()
{
return Socialite::driver('facebook')->redirect();
}
public function callback(SocialAuthService $service)
{
$user = $service->createOrGetUser(Socialite::driver('facebook')->stateless()->user());
auth()->login($user);
return redirect()->intended('/');
}
}
And the code for the service :
<?php
namespace App\Services;
use Laravel\Socialite\Contracts\User as ProviderUser;
use Myproject\Users\User;
use Myproject\Users\SocialLogin;
class SocialAuthService
{
public function createOrGetUser(ProviderUser $providerUser)
{
$account = SocialLogin::where('provider', '=', 'facebook')
->where('provider_user_id', '=', $providerUser->getId())
->first();
if ($account) {
return $account->user;
}
$user = User::where('email', '=', $providerUser->email)->first();
if (!$user) {
$fullname = explode(' ', $providerUser->getName());
$user = User::create([
'email' => $providerUser->getEmail(),
'firstname' => $fullname[0],
'lastname' => $fullname[1],
'password' => md5(rand(1, 9999)),
]);
}
$account = new SocialLogin([
'provider_user_id' => $providerUser->getId(),
'provider' => 'facebook'
]);
$account->user()->associate($user);
$account->save();
return $user;
}
}
And finally the Model :
<?php
namespace Myproject\Users;
use Illuminate\Database\Eloquent\Model;
use Myproject\Users\User;
class SocialLogin extends Model
{
protected $table = 'social_logins';
protected $fillable = ['user_id', 'provider_user_id', 'provider'];
public function user()
{
return $this->belongsTo(User::class);
}
}
When we're trying to connect via Facebook, the information is correctly insert in Database, and the callback URL set on Facebook Developers correspond to what we have in our .env, so the redirection is correctly done but at the end we don't have any session created for the user.
I think the issue comes from cross-domain, here are the interesting parts of our .env file :
APP_URL=https://www.website.com
APP_DOMAIN=website.com
SESSION_DOMAIN=.website.com
CACHE_DRIVER=redis
SESSION_DRIVER=redis
SESSION_LIFETIME=120
FACEBOOK_REDIRECT=https://www.website.com/callback/facebook
GOOGLE_REDIRECT=https://www.website.com/auth/google/callback
And our routing on web.php :
Route::domain('{subdomain}.{domain}')->middleware('locale')->group(function () {
Route::get('/callback/facebook', 'Auth\SocialAuthController#callback');
Route::get('/redirect/facebook', 'Auth\SocialAuthController#redirect');
});
I really think the issue is located on routing or SESSION_DOMAIN, but we tried to :
delete the session domain
routing outside the middleware locale, in a middleware auth
It still doesn't affect the login.

Laravel file upload not working, and have no idea why

MODEL:
namespace App;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
class product extends Model
{
public function create(Request $request) {
$file = $request->file('photo');
if ( $request->hasFile('photo') && $request->file('photo')->isValid() )
{
$extension = $file->extension();
$name = 'bjdsakbhdebkhdabhkedbhe'.$extension;
$path = $file->storeAs('public/images',$name);
}
else {
return 'error';
}
product::create([
'photo' => $path,
]);
}
protected $fillable = ['name', 'price', 'roast', 'origin', 'photo', 'stock'];
}
CONTROLLER
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\product;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
class adminController extends Controller
{
public function __construct() {
$this->middleware('auth');
}
public function create(Request $request) {
ini_set('max_execution_time', 300);
$validatedData = $request->validate([
'photo' => 'required|file|image'
]);
$new = new product;
$new->create($request);
}
}
I am trying to upload a file image. I have reworked the above code several times and an error is thrown. Absolutely NO idea why the file is not uploading. It is not a server error. File size and time allowed have been adjusted.
Why are you calling product::create inside your create method in product class? This causes an infinite recursion.

Undefined property: Illuminate\Validation\Validator::$errors in laravel

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

Resources