Call to undefined relationship [] on model [] - php

I have made hasOne relationship in my Model and it is working fine with following query in driver controller:
$drivers = Driver::with('vehicleInfo')->first()->toArray();
Driver Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Driver extends Model
{
// from_location_id
public function vehicleInfo()
{
return $this->hasOne('App\Vehicle','id','vehicle_id');
}
}
But when I try to use same code in AuthController which is generated by Laravel Auth it is giving me error of undefined relationship.
I have included model in AuthController. Which is as follows:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Carbon\Carbon;
use App\User;
use App\Role;
use App\Driver;
class AuthController extends Controller
{
public function login(Request $request)
{
$request->validate([
'mobile' => 'required|string',
'password' => 'required|string',
'remember_me' => 'boolean'
]);
$credentials = request(['mobile', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
// print_r($user);
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
$user_details = User::find($user->id);
if($user_details->actual_user_id>0){
// find driver details
// var_dump(Driver::with('vehicleInfo'));
$driver_details = Driver::with('vehicleInfo')->first()->toArray();
// var_dump($driver_details);
}else{
$driver_details = "";
}
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString(),
'user_details'=>$user_details->toArray(),
'driver_details'=>$driver_details
]);
}
}
My relationship is public.
Please help.

Related

Spatie assignRole not working (Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::sync())

Spatie user role permissions not working
Here is my RoleController.php
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
public function saveUserRoles(Request $request)
{
$validator = Validator::make($request->all(), [
'role_name' => 'required|string|unique:roles,name',
]);
if ($validator->fails()) {
alert()->error(trans($validator->messages()->all()[0]));
return back();
}
$role = new Role;
$role->name = $request->role_name;
$role->guard_name = config('auth.defaults.guard');
$role->save();
alert()->success(trans('New Role Created Successfully!'));
return redirect()->route('admin.add.user.roles');
}
User Model
User.php
use Spatie\Permission\Models\Role;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
class User extends Authenticatable
{
use Notifiable;
use SoftDeletes, HasApiTokens;
use HasRoles;
protected $fillable = [
'user_id', 'profile_image', 'name', 'email', 'address','phone','location','role_id','auth_type', 'password','status'
];
protected $hidden = [
'password', 'remember_token',
];
public function role()
{
return $this->belongsToMany(Role::class, 'role_id');
}
}
UserController
UserController.php
use Spatie\Permission\Models\Role;
use App\Http\Requests\UserCreateRequest;
public function saveUser(UserCreateRequest $request)
{
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'role_id' => $request->role_id,
'status' =>0,
]);
$role = Role::find($request->role_id);
$user->assignRole([$role->name]);
}
When i try to create a new user it shows an error
BadMethodCallException
Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::sync()
Here only need role option without any permissions
Here is your solution, as given in the documentation.

Laravel passport doesn't create User

I'm trying to register a user via HTTP POST request with PHP Laravel.
Here is my AuthController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\User;
use Illuminate\Support\Facades\Validator;
class AuthController extends Controller
{
public $successStatus = 200;
public function register(Request $request)
{
$request->validate([
'name' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string|confirmed'
]);
$user = new User([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password)
]);
$user->save();
$message['success'] = 'Created Account Successfully';
return response()->json([
'message' => $message
], 201);
}
public function login(Request $request){
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string'
]);
$credentials = request(['email', 'password']);
if(Auth::attempt($credentials)){
$user = Auth::user();
$message['token'] = $user->createToken('MyApp')->accessToken;
$message['token_type'] = 'Bearer';
$message['experies_at'] = Carbon::parse(Carbon::now()->addWeeks(1))->toDateTimeString();
$message['success'] = 'Logged in successfully';
return response()->json(['message' => $message], $this->successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
}
And my routes/api.php:
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
Route::post('/users', [AuthController::class, 'register']);
When I send a POST request to http://localhost:8080/api/users/ with name,email and passport parameters, it returns 200 response instead of 201. And it's showing the index page of Laravel, not the response. I checked the database, and user is not created.
Can you help me with what I'm missing?
You could try to change the way you do the route. For exemple:
Route::post('users', 'App\Http\Controllers\UsersController#register');
I dont really get why you do: public $successStatus = 200;
Maybe try to remove this line.

How come I can't get logged in user's bearer token to verify auth using Passport?

I have two completely separate code bases: React.js on the frontend and Laravel on the backend
I'm trying to verify the currently logged in user in order to store the filename that's being uploaded associated with the currently logged in user into my db.
In my logs I'm getting this error: local.ERROR: Call to a member function photos() which means auth()->user() is the problem but I just can't see how. I've tried too many ways to list here in terms of trying to rectify this problem. What am I doing wrong?
I'll list some things I've tried:
in the if() condition inside FileUploadController - if(auth()->user()), if(Auth::guard(api)->check()), if(Auth::check()).
Here's my FileUploadController code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FileUploadController extends Controller {
public function uploadTest(Request $request) {
if($request->bearerToken()) {
auth()->user()->photos()->create([
'file_path' => $request->file('fileToUpload')->getClientOriginalExtension()
]);
return "file uploaded";
}
return "failed uploading";
}
}
Here's my User model:
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use Notifiable, HasApiTokens;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function photos() {
return $this->hasMany(Photo::class);
}
}
Here's my Photo model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Photo extends Model
{
public function user() {
return $this->belongsTo(User::class);
}
}
Here's code for logging in the user inside my AuthController:
public function login(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
'remember_me' => 'boolean'
]);
$credentials = request(['email', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
$request->session()->put("user", $user);
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString(),
$user
]);
}

Laravel Cashier & Laravel Passport - Can't Call both Traits

I am trying to create an API. Using Laravel Cashier(With Stripe) & Laravel Passport.
public $successStatus = 200;
public function index(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 401);
}
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['name'] = $user->name;
$success['email'] = $user->email;
$stripeToken = 'tok_visa';
\Stripe\Stripe::setApiKey(env(STRIPE_SECRET));
try
{
$user->newSubscription('monthly')->create($stripeToken, [
'email' => $user->email, 'description' => 'Our First Customer'
]);
return response()->json(['success' => $success], $this->successStatus);
}
catch(Exception $e)
{
return response()->json(['success' => $success], $this->successStatus);
}
"message": "Call to a member function createToken() on null",
"exception": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",
"file": "/Users/Taylor/Documents/Websites/storingcompany/api/app/Http/Controllers/Register.php",
"line": 32,
"trace": [
Is there something That I am missing here? I am not able to call the Billable model trait from the user. In my controller it shows newSubscription not found in Authentiable instead of Billable.
My user Class:
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Cashier\Billable;
class User extends Authenticatable
{
use Billable;
use HasApiTokens;
use Notifiable;
This isn't because of not 'using' a trait, this is because the $user variable is null.
You have a line of code that creates a new User record in the database. The immediate next line, you are trying to get the current authenticated user. I would assume this is some registration or signup process so there wouldn't be an authenticated user as they don't exist in the system yet.
$user = User::create(...);
$user = Auth::user(); // what do you expect this to be, besides `null`
$user->anyMethodEver(); // Call to a member function ... on null.

Laravel 5 Auth::attempt() always failing

my Auth::attempt() returning fail everytime, I'm using my own subscribers table, i have already changed settings in config/auth.php to use subscribers table.
below is my logincontroller
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Subscriber;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
class LoginController extends Controller
{
public function login()
{
$email = Input::get('email');
$password = Input::get('password');
// $subscriber = Subscriber::where('email', $email)->first();
// $checked = Hash::check($password, $subscriber->pass);
if (Auth::attempt(['email' => $email, 'pass' => $password]))
{
return 'it workedddd.';
}
else
return 'failed';
}
}
subscriber model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Subscriber extends Model
{
protected $fillable = [
'firstname',
'lastname',
'email',
'pass',
'phone',
'address',
'city',
'state',
'zip'
];
protected $hidden = ['password', 'remember_token'];
}
subscriber controller
<?php
namespace App\Http\Controllers;
use App\Subscriber;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Requests;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
class SubscribersController extends Controller
{
public function newSubscriber(Request $request) //function to register new subscriber
{
$validator = Validator::make($request->all(), [
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required|email|unique:subscribers,email',
'password' => 'required|min:5',
'address' => 'required',
'city' => 'required',
'state' => 'required',
'zip' => 'required',
'phone' => 'required|unique:subscribers,phone'
]);
if ($validator->fails()) {
return redirect('/register')
->withErrors($validator)
->withInput();
}
$subscriber = new Subscriber();
$subscriber->firstname = Input::get('firstname');
$subscriber->lastname = Input::get('lastname');
$subscriber->email = Input::get('email');
$subscriber->pass = Hash::make(Input::get('password'));
$subscriber->address = Input::get('address');
$subscriber->city = Input::get('city');
$subscriber->state = Input::get('state');
$subscriber->zip = Input::get('zip');
$subscriber->phone = Input::get('phone');
$subscriber->trial_time = 30;
$subscriber->date_signed_up = Carbon::now();
$subscriber->next_bill_date =Carbon::now()->addMonth(1);
$subscriber->account_status = 'trial';
$subscriber->save();
return $subscriber;
}
}
routes
Route::get('/', function () {
return view('home');
});
Route::post('/', 'LoginController#login');
Route::get('contact', function() {
return view('contact');
});
Route::get('register', function() {
return view('register');
});
Route::post('register', 'SubscribersController#newSubscriber');
Route::get('feedback', function() {
return view('feedback');
});
Route::get('dashboard', array(
'before' => 'auth.basic',
function(){
return view('dashboard.user');
}));
When using Auth::attemp()You can't do:
Auth::attempt(['email' => $email, 'pass' => $password])
It should be:
Auth::attempt(['email' => $email, 'password' => $password])
So in your case you should add the following to your User model:
public function getAuthPassword()
{
return $this->attributes['pass'];
}
In your newSubscriber method change
$subscriber->pass = Hash::make(Input::get('password'));
to
$subscriber->pass = bcrypt(Input::get('password'));
Your Subscriber model should look like this..
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class Subscriber extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
protected $fillable = [
'firstname',
'lastname',
'email',
'pass',
'phone',
'address',
'city',
'state',
'zip'
];
protected $hidden = ['pass', 'remember_token'];
public function getAuthPassword()
{
return $this->pass;
}
}
Hope this will work.

Categories