ErrorException Trying to get property 'User' of non-object ( laravel ) - php

I am getting the error:
ErrorException Trying to get property 'User' of non-object
from the statements below which don't seem to work:
$user = Mobile::find(3)->User;
dd($user);
rest of the code is as follows:
usercontroller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Mobile;
use Hash;
class UserController extends Controller
{
public function addUserMobile()
{
$user = new User;
$user->name = "Test Name";
$user->email = "test#mnp.com";
$user->password = Hash::make("12345678");
$user->save();
$mobile = new Mobile;
$mobile->mobile = '123456789';
$user->mobile()->save($mobile);
}
public function index()
{
// get user and mobile data from User model
$user = User::find(3);
// var_dump($user->name);
// var_dump($user->mobile->mobile);
// // get user data from Mobile model
$user = Mobile::find(3)->User;
dd($user);
// // get mobile number from User model
// $mobile = User::find(3)->mobile;
// dd($mobile);
}
}
mobile.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* 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 mobile()
{
return $this->hasOne(Mobile::class);
// note: we can also inlcude Mobile model like: 'App\Mobile'
}
}
mobile table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateMobilesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('mobiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('mobile');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('mobiles');
}
}
mobile database
user database
"3" is user_id btw.

The problem is you are querying the Mobile with id 3 (which does not exist) and then calling the user relation.
$user = Mobile::find(3)->user;
Since Mobile::find with an id that doesn't exist returns null, you are calling ->user on null, and you will get the error you mentioned.
Also, you should add a belongsTo relation in your Mobile model:
public function user()
{
return $this->belongsTo(User::class);
}
Now, after fixing your query to use user_id, you can do:
$user = Mobile::where('user_id', 3)->first()->user;

Related

How can i get data using Eloquent Relationships in laravel

I need to get data from the teaching_subjects table to my Vue file according to teacher table data. I have created the relationship with the TeachingSubject model and Teacher model.
This is my Teacher Model,
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Teacher extends Model
{
protected $table = 'teacher';
protected $fillable = [
'firstName',
'lastName',
'teacherUserName',
'contactNo',
'teacherEmail',
'gender',
'teaching_expirence',
'Qualifications',
'description',
'speakEnglish',
'speakJapan',
'password',
'status',
];
public function approvalStatus(){
return $this->belongsTo(ApprovalStatus::class);
}
public function teachingSubject(){
return $this->hasMany(Teacher::class);
}
}
And this is my TeachingSubject Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class TeachingSubject extends Model
{
protected $table = 'teaching_subjects';
protected $fillable = [
'teacher_id',
'subject_id',
'lesson_fee'
];
public function teacher(){
return $this->hasMany(Teacher::class);
}
public function subject(){
return hasMany(Subject::class);
}
}
This is my Subject model,
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Subject extends Model
{
protected $table = 'subject';
protected $fillable = [
'subject',
'grade_id',
'no_of_teachers',
'status'
];
public function teachingSubject(){
return belongsTo(TeachingSubject::class);
}
}
This is my Teching_subjects migration file
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTeachingSubjectsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('teaching_subjects', function (Blueprint $table) {
$table->integer('id')->unsigned()->autoIncrement();
$table->integer('teacher_id')->unsigned();
$table->integer("subject_id")->unsigned();
$table->float("lesson_fee")->nullable();
$table->timestamps();
$table->foreign('teacher_id')
->references('id')->on('teacher');
$table->foreign('subject_id')
->references('id')->on('subject');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('teaching_subjects');
}
}
I need to get the date(created_at), teacher_name, lesson and lesson_fee using TeachingSubjectController.
for example if You want to get user that made the comment, so get that user from the comment object.
Try this
$user = User::find(1);
$posts = $user->posts;
foreach ($posts as $post) {
foreach ($post->comments as $comment) {
echo $comment->commentcontent;
echo $comment->users;
}
}

Subscription won't update in database after subscription is updated in Stripe using Laravel Cashier and Jenssegers MongoDB

I am having trouble getting my new subscription to be updated in MongoDB Database. Im using Laravel Cashier, Stripe, and Jenssegers MongoDB.
In the stripe dashboard, users have been successfully added as customers and subscribers.
Here is the ERROR:
[23:24:17] LOG.error: Call to a member function prepare() on null
{"userId":"4ec1b45d36623t2269477d0...
Here is where the ERROR lives:
return true;
}
$statement = $this->getPdo()->prepare($query);
$this->bindValues($statement, $this->prepareBindings($bindings));
Here is my controller:
namespace App\Http\Controllers;
use App\Plan;
use App\User;
use Exception;
use Illuminate\Http\Request;
class CheckoutController extends Controller
{
/**
* The collection name
*
* #var array
*/
public function checkout($plan_id)
{
$plan = Plan::findOrFail($plan_id);
$intent = auth()->user()->createSetupIntent();
return view('billing.checkout', compact('plan', 'intent'));
}
public function process(Request $request)
{
$plan = Plan::findOrFail($request->input('billing_plan_id'));
try {
auth()->user()->newSubscription($plan->name, $plan->stripe_plan_id)-
>create($request->input('payment-method'));
return redirect()->route('billing')->withMessage('Subscribed Successfully');
} catch (Exception $e) {
return redirect()->back()->withError($e->getMessage());
}
}
Here is My User Model:
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Jenssegers\Mongodb\Auth\User as Authenticatable;
use Laravel\Cashier\Billable;
use Illuminate\Foundation\Auth;
class User extends Authenticatable
{
use Billable, Notifiable;
protected $connection = 'mongodb';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'username', 'password', 'phone', 'last_login_at',
'last_login_ip',
];
/**
* The collection name
*
* #var array
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $dates = ['deleted_at'];
/**
* 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',
];
}
Here is My Plan Model:
namespace App;
use Jenssegers\Mongodb\Eloquent\Model;
/**
* #method static findOrFail($plan_id)
*/
class Plan extends Model
{
protected $fillable = [
'name',
'price',
'stripe_plan_id'
];
}
Here is my Subscription Migration:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Migrations\Migration;
use Jenssegers\Mongodb\Schema\Blueprint;
class CreateSubscriptionsTable extends Migration
{
/**
* The name of the database connection to use.
*
* #var string
*/
protected $connection = 'mongodb';
public function up()
{
Schema::create('subscriptions', function (Blueprint $collection) {
$collection->bigIncrements('id');
$collection->unsignedBigInteger('userid');
$collection->string('name');
$collection->string('stripe_id');
$collection->string('stripe_status');
$collection->string('stripe_plan')->nullable()->change();
$collection->integer('quantity')->nullable()->change();
$collection->timestamp('trial_ends_at')->nullable();
$collection->timestamp('ends_at')->nullable();
$collection->timestamps();
$collection->index(['user_id', 'stripe_status']);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('subscriptions');
}
}
Please help me figure out the source of this issue and how to solve it.
Make sure your model (i'm guessing it's a model but you didn't mention / show it) that is calling $this->getPdo() is extending Jenssegers eloquent model class and not Laravels.
For example:
Replace
class MyModel extends Model
With
class MyModel extends \Jenssegers\Mongodb\Eloquent\Model
Partial Solution:
Although I am getting the same error below
"Call to a member function prepare() on null {"userId":"4ec1b45d36623t2269477d0...".
In order to get the Subscription to update in the database I went into the Subscription.php file in Cashier and I replaced
use Illuminate\Database\Eloquent\Model;
with
use Jenssegers\Mongodb\Eloquent\Model;
This will fix database update issue, but something wierd is still going on in the Connection.php file causing the error.
$statement = $this->getPdo()->prepare($query);

Too few arguments to function Illuminate\Database\Eloquent\Model::setAttribute(), 1 passed

i want to ask about error "Too few arguments to function Illuminate\Database\Eloquent\Model::setAttribute(), 1 passed "
i try to register users, i use php artisan make:auth to build my authentication. But, i add one field in users migration. and i try to use uuid. this is my code :
User Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Traits\Uuids;
class User extends Authenticatable
{
use Notifiable;
use Uuids;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $guarded = ['id'];
protected $table = 'users';
protected $fillable = [
'name', 'email', 'password','phone_number',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Register Controller
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'phone' => 'required|numeric|min:8',
'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required|same:password',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'phone_number' => $data['phone'],
'password' => Hash::make($data['password']),
]);
}
}
Users Migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->uuid('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->integer('phone_number');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Uuids Trait
<?php
namespace App\Traits;
trait Uuids
{
/**
*
*/
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->{$model->uuid} =
str_replace('-', '', \Uuid::generate(4)->string);
});
}
}
Please give me advice. Thank You.
I can't find any reference about property or magic property you wrote as below (like a method getUuidAttribute for example)
$model->{$model->uuid} = str_replace('-', '', \Uuid::generate(4)->string);
So, I assume above code would compiled as
$model->{null} = str_replace('-', '', \Uuid::generate(4)->string);
I guess you're looking for $model->id which has the type of database column as a uuid. But, obviously, you can't have a dynamic database column name as it is wrong at all. Example of dynamic column if your snippet is working properly
$model->'6b324d55-433c-455a-88b6-feb2ee6c3709' = 'c3bec822-e5ee-4d91-b1a3-f5f552fd004a';
Something isn't right, right? It would be better if it look like this.
$model->id = 'c3bec822-e5ee-4d91-b1a3-f5f552fd004a';
And of course, make your latest snippet be something as follow
<?php
namespace App\Traits;
trait Uuids {
// to make model run this 'boot' method, append it with your trait name
protected static function bootUuids() { // <-- bootUuids
// parent::boot();
static::creating(function ($model) {
$model->id = str_replace('-', '', \Uuid::generate(4)->string);
});
}
}
Assuming your tables use UUID for primary key
$table->uuid('id')->primary();
Review your trait by setting the value directly to the id
<?php
namespace App\Traits;
use Illuminate\Support\Str;
trait UsesUuid
{
protected static function bootUsesUuid()
{
static::creating(function ($model) {
if (! **$model->id**) {
**$model->id** = (string) Str::uuid();
}
});
}
public function getIncrementing()
{
return false;
}
public function getKeyType()
{
return 'string';
}
}
Now use trait in your model
<?php
namespace App\Models;
use App\Traits\UsesUuid;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Group extends Model
{
use HasFactory;
**use UsesUuid;**
The full post is here
Create good solutions out there guys :)

Relation one to many it doesn't work

https://imgur.com/a/ob9rjIz
There are two tables one called user and another called user_relation_user
My relation is an user to many user_relation_user and in my migration. I want to create 10 user with php artisan tinker so i run factory(App\User::class, 10)->create(); at the end i access to my database so do select * from users there are 10 users but in user_relation_user isn't 10 id or it's empty
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Administrator extends Model
{
protected $table = 'user_relation_user';
protected $primaryKey = 'id';
protected $fillable = ['user_id'];
public function users(){
return $this->belongsTo(User::class,'user_id');
}
}
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* 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',
];
public function administrator(){
return $this->hasMany(Administrator::class,'user_id');
}
}
//hasMany
My migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUserRelationUserTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('user_relation_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('user_id_admin')->unsigned();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*foreign
* #return void
*/
public function down()
{
Schema::dropIfExists('user_relation_user');
}
}
The relation you define is correct,you just need to define a relation in user model as well.
Example:
Suppose you are developing a blog system where user can post blogs.
then there will be two models user model and blog model
In User model you have to define user relation as below:
public function blogs()
{
return $this->hasmany(Blog::class);
}
Then in blogs model
public function users()
{
return $this->belongsTo(User::class);
}

Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name laravel 5.4

Hi following are my relations
User Model
public function loginlogout()
{
$this->HasMany("App\Models\LoginLogoutLogs");
}
and this is my LoginLogoutLogs Model
public function users()
{
return $this->belongsTo('App\Models\User');
}
I am trying to access name from Users like this
$loginLogoutLogs = LoginLogoutLogs::all();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->users()->name);
}
but i am getting this error
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name
EDIT Adding Models
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Session;
use Illuminate\Support\Facades\DB;
class User extends Authenticatable
{
use Notifiable;
use EntrustUserTrait;
protected $table = 'tbl_users';
protected $primaryKey = 'id';
protected $guarded = ['id'];
const API = 'api';
const WEB = 'web';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'last_login', 'Address', 'Age', 'DateOfBirth', 'created_by', 'deleted_by'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'is_admin' => 'boolean',
];
public function isAdmin()
{
return $this->is_admin;
}
static function GetUserNamebyID($id)
{
$name = User::select("name")->where(["id" => $id])->pluck('name');
if (isset($name[0])) {
return $name[0];
} else {
return '';
}
}
public function loginlogout()
{
$this->HasMany("App\Models\LoginLogoutLogs", 'userID');
}
public function company()
{
$this->HasMany("App\Models\Company");
}
}
And now LoginLogouts Model
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Illuminate\Database\Eloquent\Model;
use Session;
use Illuminate\Support\Facades\DB;
class LoginLogoutLogs extends Model
{
use Notifiable;
use EntrustUserTrait;
protected $table = 'tbl_users_logs';
protected $primaryKey = 'id';
protected $guarded = ['id'];
const API = 'api';
const WEB = 'web';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'userID','is_accpeted','type','addedFrom'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'is_admin' => 'boolean',
];
public function isAdmin()
{
return $this->is_admin;
}
// change company to hasmany
public function user()
{
return $this->belongsTo('App\Models\User');
}
}
simply change your part of
dd($loginLogoutLog->users()->name);
into
dd($loginLogoutLog->users->name);
remove the bracket on users, its the easy fix.
here we obtain a property, not a function.... (although in the model its defined as function)
Easy fix:
$loginLogoutLogs = LoginLogoutLogs::all();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->users->name);
}
You want to access the relationship entities, as opposed to the relationship model.
By using users(), your code thinks you are trying to call a name() method on the users model, as opposed to your users method on the LoginLogoutLogs class.
You need to change your relationship with user adding the foreign key in LoginLogoutLogs:
public function user()
{
return $this->belongsTo('App\Models\User', 'userID');
}
Also ensure that you call user insted of users
$loginLogoutLogs = LoginLogoutLogs::all();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->user->name);
}
And if you want to perform use eager loading:
$loginLogoutLogs = LoginLogoutLogs::with('user')->get();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->user->name);
}
Remove () when you are getting the child model and add a second parameter to belongsTo.
Here you are:
Migrations:
// Parent migration (create_clients_table):
Schema::create('clients', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
// Child migration (create_payments_table):
Schema::create('payments', function (Blueprint $table) {
$table->unsignedBigInteger('client_id');
$table->foreign('client_id')
->references('id')
->on('clients')
->onDelete('cascade');
});
Models relationship:
// Child (Client Model)
public function owner()
{
return $this->belongsTo(User::class, 'user_id');
}
// Parent (User Model)
public function clients()
{
return $this->hasMany(Client::class);
}
Data output:
// Route:
Route::get('/client/{id}/payments', [PaymentController::class, 'paymentsOfClient']);
// In controller (PaymentController):
/**
* Display a listing of the payments of specified Client.
*
* #param string $id
* #return \Illuminate\Http\Response
*/
public function paymentsOfClient($id)
{
$client = Client::find($id);
// check permissions
if (auth()->user()->id !== $client->owner->id) {
return;
}
$payments = $client->payments()->paginate(20);
return response()->json($payments);
}

Categories