I get this error when i try to run my Laravel
Class 'Menumodel' not found
in HasRelationships.php (line 487)
Here is my data structure
And this is MainComposer.php
<?php
namespace App\Http\ViewComposers;
use Illuminate\View\View;
use App\Menumodel as menu;
class MainComposer
{
public $items = [];
public function __construct()
{
$this->items = menu::tree();
}
public function compose(View $view)
{
$view->with('items', end($this->items));
}
}
MenuModel
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Menumodel extends Model
{
//
public $table = 'Menu';
protected $fillable = ['MenuParent','MenuName','MenuPath','MenuIcon','MenuOrder','RouteName'];
public function parent() {
return $this->hasOne('Menumodel', 'MenuCode', 'MenuParent');
}
public function children() {
return $this->hasMany('Menumodel', 'MenuParent', 'MenuCode');
}
public static function tree() {
return static::with(implode('.', array_fill(0, 4, 'children')))->where('MenuParent', '=', NULL)->get();
}
}
I aldredy try this use \App\Menumodel as menu; but still no different. How can i fix it ?
Your relationships are incorrect. You need to provide the full class namespace.
return $this->hasOne(Menumodel::class, '...', '...');
return $this->hasMany(Menumodel::class, '...', '...');
I've also removed your local and foreign keys because if using Laravel, these are typically snake_case, not StudlyCase, so you may need to double check those too.
Related
I had the component model. This model had a column as the quantity which means total quantity. I want to find the available quantity of components. So I want to create a static function in the component model.How to create it?
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ComponentItem extends Model
{
use HasFactory;
protected $guarded = [];
// Link the Component Type table
public function component_type()
{
if ($this->component_type_id != null) return $this->belongsTo(ComponentType::class, 'component_type_id', 'id');
return null;
}
public function inventoryCode()
{
return $this->component_type->inventoryCode() . "/" . $this->id;
}
// Return the relative URL of the thumbnail
public function thumbURL()
{
if ($this->thumb != null) return '/img/component_items/' . $this->thumb;
return null;
}
public function orders()
{
return $this->belongsToMany(Order::class,ComponentItemOrder::class);
}
public static function componentCount(){
return
}
}
//------------------------------//
//below is the controller index function code //
//------------------------------//
public function index($from, $to,$id)
{
$data=Attendance::where('attendance_date','>=',$from)
->where('attendance_date','<=',$to)
->with('userAttendance')//--> **I need to pass the $id to this function in the model**
->with('admin')
->get()
//---------------------------------//
//below is the model code //
//----------------------------------//
class Attendance extends Model
{
protected $table = "attendances";
protected $fillable=[
'attendance_date',
'admin_id',
];
//---> **i need the $id passed to here**
public function userAttendance()
{
return $this->belongsToMany('App\User', 'user_attendances','attendance_id','user_id')
->withPivot(
'present_absent',
'excuse',
'attendance_key_amount',
'verified_date',
'comment',
);
}
}
just try this
Controller:
public function index()
{
$id = 50;
Product::getId(50);
}
Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public static function getId($id){
dd($id);
}
}
I created this code to work with laravel 5.8 to access a database with many foreign keys, seems like I am subverting the foreign keys, am I missing something, was hoping someone could point me in the right direction.
It works, but I think I am overdoing it and missing some eloquent shortcuts.
namespace App\Models\Entities;
use Illuminate\Database\Eloquent\Model;
class AbstractModel extends Model
{
public function isDuplicate(Model $model) {
return $model::where($model->getAttributes())->first();
}
}
///
namespace App\Models\Entities;
abstract class AbstractForeignModel extends AbstractModel {
public $timestamps = false;
public $fillable = ['value'];
public function store($value){
$foreign = $this->newInstance();
$foreign->value = $value;
if(!$this->isDuplicate($foreign)){
$foreign->save();
}
return $foreign->getId($value);
}
public function setValueAttribute($value){
$this->attributes['value'] = $value;
}
public function getId($value){
$result = self::where('value', $value)->first();
if($result){
return $result->id;
}
}
public function getValue($id){
$result = self::where('id', $id)->first();
if($result){
return $result->value;
}
}
}
///
namespace App\Models\Entities\Video;
use App\Models\Entities\AbstractForeignModel;
class ForeignModel extends AbstractForeignModel {
public function video() {
return $this->belongsTo('App\Models\Entities\Video');
}
}
Author, Description, Source, Title extend the above as empty classes
use App\Models\Entities\Video\Author;
use App\Models\Entities\Video\Description;
use App\Models\Entities\Video\Source;
use App\Models\Entities\Video\Title;
use Carbon\Carbon;
class Video extends AbstractModel {
protected $fillable = ['author_id', 'title_id', 'description_id',
'source_id', 'published_at'];
public function store($data) {
$video = new Video;
$video->author_id = $data->author;
$video->title_id = $data->title;
$video->description_id = $data->description;
$video->source_id = $data->source;
$video->published_at = $data->published_at;
if (!$this->isDuplicate($video)) {
$video->save();
}
}
public function setPublishedAtAttribute($value){
$this->attributes['published_at'] = Carbon::parse($value)->toDateTimeString();
}
public function setTitleIdAttribute($value) {
$this->attributes['title_id'] = (new Title)->store($value);
}
public function setDescriptionIdAttribute($value) {
$description = (new Description)->store($value);
$this->attributes['description_id'] = $description;
}
public function setSourceIdAttribute($value) {
$this->attributes['source_id'] =(new Source)->store($value);
}
public function setAuthorIdAttribute($value) {
$this->attributes['author_id'] = (new Author)->store($value);
}
public function getAuthorIdAttribute($value) {
$this->attributes['author_id'] = (new Author)->getValue($value);
}
public function getTitleIdAttribute($value) {
$this->attributes['title_id'] = (new Title)->getValue($value);
}
public function getDescriptionAttribute($value) {
$this->attributes['description_id'] = (new Description)->getValue($value);
}
public function getSourceIdAttribute($value) {
$this->attributes['source_id'] = (new Source)->getValue($value);
}
public function author() {
return $this->belongsTo('App\Models\Entities\Video\Author', 'author_id');
}
public function description() {
return $this->belongsTo('App\Models\Entities\Video\Description', 'description_id');
}
public function title() {
return $this->belongsTo('App\Models\Entities\Video\Title', 'title_id');
}
public function source() {
return $this->belongsTo('App\Models\Entities\Video\Source', 'source_id');
}
}
video migration file
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateVideosTable extends Migration {
public function up() {
Schema::create('videos', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('source_id');
$table->unsignedBigInteger('title_id');
$table->unsignedBigInteger('description_id');
$table->unsignedBigInteger('author_id');
$table->dateTimeTz('published_at');
$table->timestamps();
$table->foreign('source_id')->references('id')->on('sources');
$table->foreign('title_id')->references('id')->on('titles');
$table->foreign('description_id')->references('id')->on('descriptions');
$table->foreign('author_id')->references('id')->on('authors');
});
}
public function down() {
Schema::dropIfExists('videos');
}
}
The foreign key migration files follow this layout for Author, Description, Source, Title
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTitlesTable extends Migration
{
public $timestamps = false;
public function up()
{
Schema::create('titles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('value');
});
}
public function down()
{
Schema::dropIfExists('titles');
}
}
could probably create a foreign migration class and just set the variables that I need
What you're probably looking for is firstOrCreate
There are two other methods you may use to create models by mass
assigning attributes: firstOrCreate and firstOrNew. The firstOrCreate
method will attempt to locate a database record using the given column
/ value pairs. If the model can not be found in the database, a record
will be inserted with the attributes from the first parameter, along
with those in the optional second parameter.
The firstOrNew method, like firstOrCreate will attempt to locate a
record in the database matching the given attributes. However, if a
model is not found, a new model instance will be returned. Note that
the model returned by firstOrNew has not yet been persisted to the
database. You will need to call save manually to persist it.
I have created multilevel menu by this example (first reply):
How to create a database-driven multi-level navigation menu using Laravel
I'm always getting empty array. Here's my database structure (database's name is also "structure")
structure_id and parent_id are relevant.
Here's my code:
App/navigation.php
<?php
namespace App;
use DB;
use Illuminate\Database\Eloquent\Model;
class Navigation extends Model {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'structure';
public function parent() {
return $this->hasOne('structure', 'structure_id', 'parent_id');
}
public function children() {
return $this->hasMany('structure', 'parent_id', 'structure_id');
}
public static function tree() {
return static::with(implode('.', array_fill(0, 4, 'children')))->where('parent_id', '=', NULL)->get();
}
}
and the Controller:
app/http/controllers/structurecontroller.php
<?php
namespace App\Http\Controllers\Superuser;
use App\Http\Controllers\Controller;
use App\Navigation;
use App\Structure as Model;
class StructureController extends Controller
{
/**
* Allow only for logged in
* DashboardController constructor.
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
//$model = new Model();
//$items = $model->getStructure();
$items = Navigation::tree();
var_dump($items);exit;
return view('superuser.structure', ['items' => $items]);
}
}
I'm pretty sure, I have some data in database. So, what's the problem there? I'm getting always empty array from database. Thank for help
It's probably your database structure--you're declaring parent_id as NOT NULL, with a default of 0. In your tree function you then do this:
...->where('parent_id', '=', NULL)->get();
I'm going to guess that the "0" is not resolving to NULL like you intended.
// Do not forget to add import: App\structure
public function parent() {
return $this->hasOne('App\structure', 'structure_id', 'parent_id');
}
I have some models belong to Activity Model.
in my Activity.php I had
<?php
class Activity extends \Eloquent {
protected $fillable = [];
public function activity_car_nums()
{
return $this->hasMany('ActivityCarNum');
}
public function newables()
{
return $this->hasMany('Newable');
}
public function serial_codes()
{
return $this->hasMany('SerialCode');
}
public function applys()
{
return $this->hasMany('Apply');
}
}
and in SerialCode.php, I had
<?php
class SerialCode extends \Eloquent {
protected $fillable = ['code'];
public function activity()
{
return $this->belongsTo('Activity');
}
}
and in my controller, when I wrote
$serial_codes = [];
while(count($serial_codes) < $serial_code_total)
{
$code = substr(md5(uniqid(rand(), true)),0,5);
$serial_code = new SerialCode(['code' => $code]);
if(!in_array($serial_code, $serial_codes))
{
$serial_codes[] = $serial_code;
}
}
$activity->serial_codes()->saveMany($serial_codes);
it works.
But when it turns to
//this can get activity object
$activity = Activity::find($id);
//this can get the serial codes of the object above.
$serial_codes = SerialCode::whereActivityId($id)->get();
//this don't work, it returns null
$serial_codes = $activity->serial_codes;
for I really don't know why...
Can anybody help me please, and sorry for my poor English. Thank You.
(If you need any code else please tell me.)
my model code:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use DB;
class Product extends Model
{
public $table="s_products";
protected $primaryKey = 'product_id';
public function reviews()
{
return $this->hasMany('App\ProductReview');
}
public function attributes()
{
return $this->hasMany('App\AttributeMapping');
}
public function images()
{
return $this->hasMany('App\Image');
}
}
I found the reason that why my model query cannot work, because the "_" in function name.
just change
public function serial_codes()
to
public function serialcodes()
then everything will go fine.
Thank to everybody.