laravel Class 'App\Categories' not found - laravel

When I try to call a function with categories data $categories = Categories::all(); it returns an error that Class 'App\Categories' not found
Here is my CategoriesController code:
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller as BaseController;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Categories;
class CategoriesController extends BaseController
{
public function listcategories() {
$categories = Categories::all();
dd($categories);
return view('admin.list_categories')->with('listcategories',
$categories);
}
Here is my Categories model code ;
namespace App;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
class Categories extends Model
{
protected $fillable = [
'title',
'description',
'flag_image',
'status'
];
const STATUSES = [
'Active' => 'Active',
'Inactive' => 'Inactive',
];
const DEFAULT_STATUS = 'Active';
/**
* Indicates if the model should be timestamped.
*
* #var bool
*/
public $timestamps = false;
public static function rules() {
return [
'title' => 'required|string|max:255',
'status' => 'required|string|in:' . implode(",", Categories::STATUSES)
];
}}
What is the problem ? I can't get it.

Because models are autoloading via composer
in some cases you need to run
composer dump-autoload after changes in order to make it work

Related

Loading a belongs to relationship inside of a laravel resource collection

I'm having some issues loading my relationships into a ResourceCollection to be consumed by an API, I want to load blogs that each belong to a category.
The blog model which uses a belongsTo relationship
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
class BlogPost extends Model {
use HasFactory, SoftDeletes;
protected $fillable = [
'title',
'content',
'seo_title',
'seo_content',
];
public function categories(): BelongsTo {
return $this->belongsTo(BlogCategory::class);
}
}
The Category model has a hasMany to blogs
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class BlogCategory extends Model {
use HasFactory;
protected $fillable = [
'slug'
];
public function blogs(): HasMany {
return $this->hasMany(BlogPost::class);
}
}
Inside of the blog_post migration, I added a foreign key to blog_categories
$table->foreignId('category_id')->constrained('blog_categories');
Then, in my BlogPost ResourceCollection I tried loading the relationship,
#[ArrayShape(['data' => "\Illuminate\Support\Collection", 'category' => AnonymousResourceCollection::class])] public function toArray($request): array {
return [
'data' => $this->collection,
'category' => BlogCategoryCollection::make($this->whenLoaded($this->categories))
];
}
I call the collection inside of the index function of my controller
public function index(): BlogPostCollection
{
return new BlogPostCollection(BlogPost::all());
}
And when I hit the api/blogs endpoint I get the error :
Property [categories] does not exist on this collection instance.
Managed to fix it in the end.
Changed the BlogPostResourceCollection to the following
return [
'data' => $this->collection,
'categories' => BlogCategoryCollection::collection($this->whenLoaded('categories'))
];
seems to work in the end.

How to use relationship inside another relationship of other model?

I want to use public function scheduleTime() to check sechudle_time inside newsLetterSentOn() of News Model.
If this can be done,please help me regarding this.Thank you.
This is News Model
<?php
namespace Modules\Newsletter\Entities;
use Brexis\LaravelWorkflow\Traits\WorkflowTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
/**
* This is for storing news
* Class News
* #package Modules\Newsletter\Entities
*/
class News extends Model {
use WorkflowTrait;
protected $table = 'news_info';
protected $fillable = [
'title', 'header', 'description', 'status', 'created_by', 'media_url', 'media_thumbnail', 'media_type'
];
public function newsLetterSentOn() {
return $this->belongsToMany(Newsletter::class,'news_newsletters','news_id','newsletter_id')
->whereHas('scheduleTime', function($q){
$q->where('schedule_time', '<', date("Y-m-d h:i:s", time()));
});
}
}
This is Newsletter Model
<?php
namespace Modules\Newsletter\Entities;
use Illuminate\Database\Eloquent\Model;
class Newsletter extends Model
{
protected $table = 'newsletters';
protected $hidden = ['pivot'];
protected $fillable = [];
public function scheduleTime()
{
return $this->belongsTo(ScheduleTime::class,'id','newsletter_id');
}
}
You can get nested relationship with dot notation like so:
$news = News::with(['newsLetterSentOn.scheduleTime' => function($q)
$q->where('schedule_time', '<', date("Y-m-d h:i:s", time()));
])->find($id);
Then you can access it through $news like normal.
$news->newsLetterSenton->scheduleTime;

How do I interact with the four Eloquent models correctly?

The project consists of four related tables:
orders (id, status, client_email, partner_id)
order_products (id, order_id, product_id, quantity, price)
partners (id, email, name)
prods (id, name, price, vendor_id)
creating 4 models:
<?php
//App\Order.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $fillable = [
'id', 'status', 'client_email', 'partner_id',
];
public function partner()
{
return $this->belongsTo('App\Partner');
}
public function order_product()
{
//belongsToMany - server error
return $this->belongsTo('App\Prod', 'order_products');
}
public function prod()
{
return $this->belongsTo('App\Prod');
}
}
<?php
//App\Partner.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Partner extends Model
{
protected $fillable = ['id', 'email', 'name'];
public function order()
{
return $this->hasOne('App\Order');
}
}
<?php
//App\Order_product.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order_product extends Model
{
protected $fillable = ['order_id', 'product_id', 'quantity', 'price'];
public function order()
{
return $this->hasOne('App\Order');
}
}
<?php
//App\Prod.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Prod extends Model
{
protected $fillable = ['order_id', 'product_id', 'quantity', 'price'];
public function order()
{
return $this->belongsToMany('App\Order', 'order_products');
}
}
creating Order Resources:
<?php
//App\Http\Resources\Order.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Order extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'status' => $this->status,
'client_email' => $this->client_email,
'partner_id' => $this->partner_id,
'partner_name' => $this->partner->name,
//return server error
'product_id' => Prod::collection($this->order_product),
'name' => $this->prod->name,
];
}
}
creating Prod Resource:
<?php
//App/Http/Resources\Prode.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Prod extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
];
}
}
And return from Order Controller:
<?php
//App\Http\Controllers\Api\OrderController.php
namespace App\Http\Controllers\Api;
use App\Order;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Resources\Order as OrderResource;
class OrderController extends Controller
{
public function index()
{
$orders = Order::with(['partner', 'order_product', 'prod'])->get();
return OrderResource::collection($orders);
}
}
How do I get the product name in the order?
Order_product seems like a name for a pivot table. This isn't necessary in laravel because the frameworks assumes the table structure by default. The recommended approach is creating the following models:
Order
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $fillable = [
'id', 'status', 'client_email', 'partner_id',
];
public function partner()
{
return $this->belongsTo('App\Partner');
}
public function products()
{
return $this->belongsToMany('App\Product', 'order_products');
}
public function prod()
{
return $this->belongsTo('App\Prod');
}
}
Product (Prod)
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $table = 'prod';
protected $fillable = ['order_id', 'product_id', 'quantity', 'price'];
public function orders()
{
return $this->belongsToMany('App\Order', 'order_products');
}
}
and with the following resources:
OrderResource
<?php
//App\Http\Resources\Order.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class OrderResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'status' => $this->status,
'partner_id' => $this->partner_id,
'partner_name' => $this->partner->name,
'products' => ProductResource::collection($this->products),
'name' => $this->prod->name,
];
}
}
ProductResource
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class ProductResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
];
}
}
more details over many to many relations can be found in the docs.

Laravel Call to undefined method Illuminate\Database\Eloquent\Builder::privilege()

I would like to display privileges('name') instead of idPrivilege in the user collection. I have tried to add a relationship and use it in an Eloquent call but I'm getting an error.
User model
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $table = 'users';
protected $primaryKey = 'idUser';
protected $fillable = [
'name', 'email',
];
protected $hidden = [
'password', 'updated_at',
];
public function privilege()
{
return $this->hasOne(Privilege::class, 'idPrivilege', 'idPrivilege');
}
}
Privilege model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Privilege extends Model
{
protected $table = 'privileges';
protected $primaryKey = 'idPrivilege';
protected $fillable = [
'name',
];
protected $hidden = [
'updated_at',
];
public function user()
{
return $this->belongsTo(User::class, 'idPrivilege', 'idPrivilege');
}
}
UserController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
public function relationTest()
{
return User::where('idUser', 1)->privilege()->get();
}
}
I'm getting the below error when I use with('privilege') to my User collection is added privilege collection.
Call to undefined method Illuminate\Database\Eloquent\Builder::privilege().
where returns a Builder instance on which a privilege method does not exist, so you can simply use it as such:
return User::find(1)->privilege()->get();;
-- EDIT
User::find(1)->with(['privilege' => function($query) {
$query->select('name');
}])->get();
I can achieve it by using resource:
$user = User::where('idUser', 1)->with('privilege')->first();
return UserResource::make($user);
Inside UserResource:
public function toArray($request)
{
return [
'idUser' => $this->idUser,
'name' => $this->name,
'email' => $this->email,
'privilege' => $this->privilege['name'],
'createdAt' => $this->created_at,
];
}
but was hoping there is simplier method of getting that.
output:
{
"data": {
"idUser": 1,
"name": "Martin",
"email": "martin#martin.martin",
"privilege": "user",
"createdAt": "2019-05-05T01:11:43.000000Z"
}
}

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.

Resources