Class 'app\Models\Phone' not found in Laravel 8 - php

I am trying ORM one to one relationship. I dont know why it cant recognize model class phone.
code as follows.
Phone.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasOne;
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 Phone(){
return $this->hasOne('app\Models\Phone');
}
}
Phone.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
use HasFactory;
protected $table = "phones";
public function User(){
return $this->belongsTo('app\Models\User');
}
}
UserController.php
<?php
namespace App\Http\Controllers;
use App\Models\Phone;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function insert(){
$user = new User();
$user->name = 'BBB';
$user->email = 'bbb#mail.com';
$user->password = 'bbb#mail.com';
$user->save();
$phone = new Phone();
$phone->number = "445566";
$user->Phone()->save($phone);
return "RECORDS ADDED";
}
public function show($id){
$phone = User::find($id)->phone;
return $phone;
}
}
web.php
<?php
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::get('insert',[\App\Http\Controllers\UserController::class,'insert'])->name('user.insert');
Route::get('show/{id}',[\App\Http\Controllers\UserController::class,'show'])->name('user.show');

You need to fix this
public function User(){
return $this->belongsTo('App\Models\User');
}
here fix namespace app to App like that you need to fix all

namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasOne;
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 Phone(){
return $this->hasOne('App\Models\Phone');
//Better to use ::class notation for greater benefits with IDE
//return $this->hasOne(Phone::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
use HasFactory;
protected $table = "phones";
public function User(){
return $this->belongsTo('App\Models\User');
//Better to use ::class notation for greater benefits with IDE
//return $this->hasOne(User::class);
}
}
Folder/directory is app but the namespace is App
So need to change app\Models\Phone and app\Models\User to App\Models\Phone and App\Models\User
Better yet, use ::class notation for greater benefits with IDE - like easy navigation - not possible with string literals.
So instead of string literal App\Models\Phone import use App\Models\Phone statement and the Phone::class
Similarly for User import use App\Models\User and then use User::class

Related

Call to undefined method App\Models\User::createSetupIntent()

I am trying to implement subscriptions with stripe integration using cashier packages in my Laravel application. I am facing this error whenever I select a plan.
My PlanController.php file code is as followed
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Plan;
class PlanController extends Controller
{
/**
* Write code on Method
*
* #return response()
*/
public function index()
{
$plans = Plan::get();
return view("plans", compact("plans"));
}
/**
* Write code on Method
*
* #return response()
*/
public function show(Plan $plan, Request $request)
{
$intent = auth()->user()->createSetupIntent();
return view("subscription", compact("plan", "intent"));
}
/**
* Write code on Method
*
* #return response()
*/
public function subscription(Request $request)
{
$plan = Plan::find($request->plan);
$subscription = $request->user()->newSubscription($request->plan, $plan->stripe_plan)
->create($request->token);
return view("subscription_success");
}
}
After searching for solutions online I am still stuck at the same problem. Kindly help.
Some other models that might help you in finding solution are as followed:
Plan.php The model file for plans
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class plan extends Model
{
use HasFactory;
protected $fillable = [
'name',
'slug',
'stripe_plan',
'price',
'description',
];
/**
* Write code on Method
*
* #return response()
*/
public function getRouteKeyName()
{
return 'slug';
}
}
Model file for users User.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;
use Laravel\Sanctum\HasApiTokens;
use Laravel\Cashier\Billable;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
'role',
'plan',
'created_by',
'status',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Add the Billable trait from Laravel Cashier to your User model.
use Laravel\Cashier\Billable;
class User extends Authenticatable
{
use Billable, HasApiTokens, HasFactory, Notifiable;
}

db:seed can't find factory() method

I'm trying to seed two tables with the following code:
<?php
namespace Database\Seeders;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Foundation\Auth\User;
use App\Models\Role;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
User::factory(10)->create();
$roles = [
'dps',
'tank',
'healer'
];
foreach ($roles as $role) {
Role::create([
'name' => $role,
]);
}
foreach(User::all() as $user) {
foreach (Role::all() as $role) {
$user->$roles()->attach($role->id);
}
}
}
}
using php artisan db:seed, but its returning Call to undefined method Illuminate\Foundation\Auth\User::factory().
Going through User model, I have the following:
<?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;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
];
public function monstros() {
return $this->hasMany('App\Models\Monstro');
}
public function arsenais() {
return $this->hasMany('App\Models\Arsenal');
}
public function itens() {
return $this->hasMany('App\Models\Item');
}
public function roles() {
return $this->belongsToMany(Role::class);
}
}
Where we can clearly see it's calling for the Factory method with use HasFactory
What am I missing here?
Also tried to restart artisan, update the framework, dump-auto load, none of those helped.
You are calling the wrong class instead of calling the App\Models\User you are calling the Illuminate\Foundation\Auth\User. Which has the same name. You can take a look at the namespaces above.

How to show list of data based on the user in Laravel

I have two table (three actually, but in this context it's only related to these two tables), Pekerjaan and User. Both table are in eloquent. User hasMany pekerjaans, and Pekerjaan belongsTo User. In the User table it has status 'super' and 'ppk'. 'Super' is a super admin whereby it can view all data, and for 'ppk' it can only view certain data based on his/her USER_ID in Pekerjaan's table. Here is my code for User.php model:
<?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;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\Model as Eloquent;
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'username',
'satker',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
];
public function pekerjaans(){
return $this->hasMany(Pekerjaan::class);
}
}
And here is the Pekerjaan.php model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model as Eloquent;
class Pekerjaan extends Eloquent
{
use HasFactory;
protected $guarded = [];
public function penyedia(){
return $this->belongsTo(Penyedia::class, 'penyedia_id');
}
public function user(){
return $this->belongsTo(User::class, 'user_id');
}
}
Here is what I've tried in AdminController:
public function tabelpekerjaan(User $user){
if(Auth::user()->status=='super'){
$pekerjaan = Pekerjaan::with('penyedia')->paginate();
return view('admin.datapekerjaan', compact('pekerjaan'));
}else{
$pekerjaan = $user->pekerjaans;
return view('admin.datapekerjaan', compact('pekerjaan'));
}
}
Here is my code in web.php:
Route::get('/datapekerjaan',[AdminController::class,'tabelpekerjaan'])->name('datapekerjaan');
For now it shows me blank table when I logged in as 'ppk', and what I need is it will shows list of pekerjaan based on the user id. How to achieve this? Here is my table pekerjaans in database:
public function tabelpekerjaan(){
if(Auth::user()->status=='super'){
$pekerjaan = Pekerjaan::with('penyedia')->paginate();
return view('admin.datapekerjaan', compact('pekerjaan'));
}else{
$pekerjaan = Auth::user()->pekerjaans;
return view('admin.datapekerjaan', compact('pekerjaan'));
}
}
Try the above code, i guess your route model binding is in correct.

withTrashed not being applied to relation tables

I am running into this issue where I can't retrieve the soft-deleted data of the relation tables. My approach was to use the withTrashed method, but it gave me no luck whatsoever.
This is the line of code:
return response()->json($user->orders()->withTrashed()->with('order_details', 'order_details.product', 'address')->get());
It ignores what's inside the with clause. How do I fix this issue? Any help would be appreciated, many thanks!
EDIT
My Order model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Concerns\HasEvents;
class Order extends Model
{
use HasFactory, SoftDeletes, Notifiable, HasEvents;
protected $fillable = [
'user_id', 'address_id', 'total_price', 'order_status', 'is_delivered'
];
public function user() {
return $this->belongsTo(User::class, 'user_id');
}
public function product() {
return $this->belongsTo(Product::class);
}
public function address() {
return $this->belongsTo(Address::class, 'address_id');
}
public function order_details() {
return $this->hasMany(OrderDetails::class, 'order_id', 'id');
}
}
My user model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasFactory, Notifiable, SoftDeletes, 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 orders() {
return $this->hasMany(Order::class);
}
}

BadMethodCallException App\User::create() when seeding with zizaco

I'm having an error when seeding to the database using laravel 5.5 the error message is below and there is my users class and my seeder class. What is happening is that one record is being inserted at a time when calling db:seed but after the first call it says BadMethodException rest below
[BadMethodCallException]
Call to undefined method App\User::create()
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Eloquent;
class User extends Eloquent
{
use EntrustUserTrait;
/**
* 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',
];
}
<?php
use App\User;
use Faker\Factory as Faker;
use Illuminate\Database\Seeder;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
foreach (range(1, 100) as $index) {
$faker = Faker::create();
$user = User::create([
'name' => $faker->firstName . ' ' . $faker->lastName,
'email' => $faker->email,
'password' => bcrypt('secret')
]);
}
}
}
Your user model should extend
\Illuminate\Database\Eloquent\Model
Or
\Illuminate\Foundation\Auth\User
You are extending Eloquent
laravel/laravel repository: https://github.com/laravel/laravel/blob/master/app/User.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',
];
}
Your User class needs to extend to Model class
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
...
}
EDIT
This is my User
<?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 User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
}
Hope it helps!

Categories