Class 'App\Post' not found [duplicate] - php

This question already has answers here:
Laravel - Model Class not found
(11 answers)
Closed 9 months ago.
I am working on laravel 5.2 AJAX Pagination with Jquery I have defined my post class as
Post.php
<?php
class Post extends Eloquent
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'posts';
/**
* Define guarded columns
*
* #var array
*/
protected $guarded = array('id');
}
BlogController.php
<?php
class BlogController extends Controller
{
/**
* Posts
*
* #return void
*/
public function showPosts()
{
$posts = Post::paginate(5);
if (Request::ajax()) {
return Response::json(View::make('posts', array('posts' => $posts))->render());
}
return View::make('blog', array('posts' => $posts));
}
}
Kindly help me where to paste this class to go right .
I know its error that model class is missing but dont know how to get rid of
My code structure is in snapshot
Thanks

Your Post.php model should be
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
//
}
In BlogController.php file add below lines on top
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Post;
Read this:- https://laravel.com/docs/5.2/eloquent

Add the namespace in the beginning of file like and use Model rather than eloquent class to extend
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
}
It will work for laravel >5.0 .

You should add below statements at top of your Post.php file, like this...
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
Now, in BlogController.php add the below statement at top of the file, like...
<?php
use App\Post;
will work definitely in Laravel 5>=

Related

Laravel seeder : Call to undefined method Illuminate\Notifications\Notification::getConnectionName()

I have a many to many relationship between two models:
User
namespace App\Models;
class User extends Model
{
use HasApiTokens, Notifiable,hasFactory;
/**
* The attributes that are mass assignable.
*
* #var array
*/
];
}
Notification
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Notification extends Model
{
/**
* #var array
*/
protected $guarded = ['id'];
use HasFactory;
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class);
}
}
I created a factory for each model and a Seeder which calls the two factories in order to create users and attach notifications to each one of them.
NotificationUserSeeder:
<?php
namespace Database\Seeders;
use App\Models\Notification;
use App\Models\User;
use Illuminate\Database\Seeder;
class MockNotificationUser extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
}
}
I am getting this error when running db:seed:
Call to undefined method Illuminate\Notifications\Notification::getConnectionName()
Since you have named model name as Notification .And while importing in seeder class ,it look like you have imported
use Illuminate\Notifications\Notification;
instead of
use App\Models\Notification;
Updated
The issue is with User model due to conflict in model name and Illuminate Notification facade's. Notification facade not used in User model so better to remove notification import. Suppose if you are using Notification illuminate then you can use as alias any one of the imports

Laravel, Call to undefined function Database\Seeders\factory()

I get the title error when I run command:
php artisan db:seed
My screenshot:
I have no idea where this problem comes from. I was searching for code examples and solution but I haven't found anything :(
ArticlesTableSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
// use Laracasts\TestDummy\Factory as TestDummy;
class ArticlesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory(App\Models\Article::class, 30)->create();
}
}
ArticleFactory.php
<?php
namespace Database\Factories;
use App\Models\Model;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class ModelFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = App\Models\Article::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
return [
'title' => $faker->text(50),
'body' => $faker->text(200)
];
}
}
DatabaseSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call(ArticlesTableSeeder::class);
}
}
Thank you in advance for your help!
In laravel 8 the default route namespace was removed.
Try to change:
ArticlesTableSeeder.php:
factory(App\Models\Article::class, 30)->create();
to:
\App\Models\Article::factory()->count(30)->create();
ArticleFactory.php:
protected $model = App\Models\Article::class;
to:
protected $model = \App\Models\Article::class;
and you will probably have to change:
'title' => $faker->text(50),
'body' => $faker->text(200)
to:
'title' => $this->faker->text(50),
'body' => $this->faker->text(200)
All suggestions that were mentioned here are correct.
Sometimes running composer require laravel/legacy-factories might fix your problem if you're using Laravel 8.
Also, in case you get an error that says Class 'Database\Factories\ArticleFactory' not found
then make sure you have class ArticleFactory extends Factory and not ModalFactory.
And make sure you're using HasFactory in the Article Model like here.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasFactory;
}
For more info: Laravel 8 Modal Factories
Try to change
factory(App\Models\Article::class, 30)->create();
to
App\Models\Article::factory()->count(30)->create();
ArticlesTableSeeder.php
<?php
namespace Database\Seeders;
use App\Models\Article;
use Illuminate\Database\Seeder;
class ArticlesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Article::factory()->times(30)->create();
}
}
ArticleFactory.php
<?php
namespace Database\Factories;
use App\Models\Article;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class ArticleFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = Article::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
return [
'title' => $this->faker->text(50),
'body' => $this->faker->text(200)
];
}
}
If you are using version 8 of laravel, look at the upgrade guide.
"Laravel's model factories feature has been totally rewritten to support classes and is not compatible with Laravel 7.x style factories. However, to ease the upgrade process, a new laravel/legacy-factories package has been created to continue using your existing factories with Laravel 8.x. You may install this package via Composer:
composer require laravel/legacy-factories"
https://laravel.com/docs/8.x/upgrade#seeder-factory-namespaces
change
‍factory(App\Models\Article::class, 30)->create(); ‍
to
\App\Models\Article::factory(30)->create();
I'm facing the same issue when I realized my model was not using the HasFactory trait.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'categories';
}
So make sure this trait is being used by your model.
If you are using version 8 of laravel you can directory use:
use App\Models\Article;
Article::factory()->count(30)->create();
composer require laravel/legacy-factories
php artisan db:seed

Load multiple models from single controller

need help laravel. I have 2 model in different folder
app\User
app\model\Role
there is no problem when i used at UsersController -> call app\User, or RolesController -> call app\model\Role
but, when i used both models on UsersController , the app\model\Role didnt work
==================== UsersController ======================
namespace App\Http\Controllers\admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use app\User;
use app\model\Role as Role;
use DataTables;
class UserController extends Controller
{
public function index(Request $request){
$data['title_page'] = 'User';
$data['roles'] = Role::all(); // this line show error
return view('admin/user', $data);
}
}
======================== app\model\Role ===================
namespace App\model;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
protected $fillable = ['id','name'];
protected $tables = 'roles';
public function users(){
return $this->belongsTo('App\User','role');
}
}
======================== app\User =======================
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $table = "users";
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','role', 'status'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function roles(){
return $this->hasOne('App\model\Role','id');
}
}
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Class 'app\model\Role' not found
Try with capital 'A' on 'App'. Some systems are case sensitive. So use App\Model\Role depending on your folder name for model. IE if your model folder is lower case, match it in the use statement.
Also, you don't need the as keyword here unless there are conflicts - you may be fine with just use App\Model\Role without the as Role.
One more item, make sure the Role class is actually in the model folder and that your namespace is at the top of the php file correctly referencing the App\Model namespace. So in your Role class make sure the caps match your use call -
<?php
namespace App\Model

Laravel 5 SQLSTATE[42S02]: Base table or view not found

I'm studing about Repository Design Pattern in Laravel and I'm using https://github.com/andersao/l5-repository to do it.
I think i install success in my project . But when i run code with repository i have some problem
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'test.nhanviens' doesn't exist (SQL: select * from nhanviens)
Table in my database is Nhanvien not Nhanviens
Here in my code
NhanvienRepository.php
<?php
namespace App\Repositories;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface NhanvienRepository
* #package namespace App\Repositories;
*/
interface NhanvienRepository extends RepositoryInterface
{
//
}
NhanvienRepositoryEloquent.php
<?php
namespace App\Repositories;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\NhanvienRepository;
use App\Entities\Nhanvien;
use App\Validators\NhanvienValidator;
/**
* Class NhanvienRepositoryEloquent
* #package namespace App\Repositories;
*/
class NhanvienRepositoryEloquent extends BaseRepository implements NhanvienRepository
{
/**
* Specify Model class name
*
* #return string
*/
public function model()
{
return Nhanvien::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
DataController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\nhanvien;
use App\Repositories\NhanvienRepository;
class DataController extends Controller
{
protected $repository;
public function __construct(NhanvienRepository $repository){
$this->repository = $repository;
}
public function DanhSach(){
var_dump($this->repository->all());
}
}
from App\Nhanvien.php Add this variable to the class:
protected $table = 'nhanvien';
Explanation: The "snake case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the nhanvien model stores records in the nhanviens table.
As stated in the official Eloquent documentation you need to specifically set the table name in your Model definition. That is, in your App\Nhanvien.php file set the following:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Nhanvien extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'Nhanvien';
}
or use
protected $table = 'nhanvien';
instead if your table name is full lowercase.
Check your migration file, maybe you are using Schema::table, like this:
Schema::table('table_name', function ($table) {
// ... });
If you want to create a new table you must use Schema::create:
Schema::create('table_name', function ($table) {
// ... });
See the Laravel migration documentation for more information.
If you are using Schema::create then please provide the contents of your migration file.
In my case, I've got rid of similar error by executing the command
php artisan config:cache

one to many relationship in Laravel5 is not working properly

I have a collection controller
looks like this
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Middleware\Role;
use Illuminate\Support\Facades\Input;
use App\User;
use App\Invoice;
use Session;
use Validator;
class CollectionController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function __construct(){
$this->middleware('role:collector'); // replace 'collector' with whatever role you need.
}
public function getPayment($invoiceid){
$id =$invoiceid;
$invoice=Invoice::where('Id', $id)->with(['payments'])->get();
return View('collectionmodule/payment')->with(array('invoice'=>$invoice));
}
}
Then I have following models
Invoice
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Invoice extends Model
{
//
protected $table = 'event_invoice';
public function payments(){
return $this->hasMany('App\paymentrecieved','invoice_id');
}
public function comments(){
return $this->hasMany('App\comments','invoice_id');
}
}
Paymentrecieved
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class paymentrecieved extends Model
{
//
protected $table = 'paymentrecieved';
public function invoice(){
return $this->belongsTo('App\Invoice');
}
}
So for every Invoice there could be multiple payments .
So in My getPayment method I am writing Query like this .
$invoice=Invoice::where('Id', $id)->with(['payments'])->get();
Its getting me the Details from Invoice table . But its not getting me any Payment Details
Any one know why is this happening , According to me I have done the relationship properly
Thanks
You use Id (with uppercase) for the primary key, but the Invoice model is looking for the id (with lowercase).
You should define the primary key in the Invoice model like this:
protected $primaryKey = 'Id';

Categories