Model is not found. Bug in Laravel Framework? - laravel-5

My Model is like this
class redModel extends Model {
public $table = 'tbl50red';
public $primaryKey = 'RedID';
public $timestamps = true;
}
and here is another model
class AddOnModel extends Model {
public $table = 'tbladdon';
public $primaryKey = 'AddOnID';
public $timestamps = true;
public function AppRed() {
return $this->hasMany("\App\Models\AddOn\Red\redModel", "AddOnID", "AddOnID");
}
}
In the controller when i run this:
$AddOns = AddOnModel
::with(array("AppRed" => function($query) use($StartDate, $EndDate) {
return $query->whereBetween("EarningDate", array($StartDate, $EndDate));
}))
->get();
I get an exception :
Class '\App\Models\AddOn\Red edModel' not found
Am I missing something?

You may try the given way...
use Illuminate\Database\Eloquent\Model;
class Application extends Model
{
public function AppRed()
{
return $this->hasMany(redModel::class);
}
}

This is not a bug in Laravel. Please read the PSR-1 Basic Coding Standard which will enable you to easily avoid this error in the future. Namely, this is the part you are violating:
Class names MUST be declared in StudlyCaps.

When I open below file:
\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php
and checked this function
public function hasMany($related, $foreignKey = null, $localKey = null)
{
$foreignKey = $foreignKey ?: $this->getForeignKey();
$instance = new $related;
$localKey = $localKey ?: $this->getKeyName();
return new HasMany($instance->newQuery(), $this, $instance->getTable().'.'.$foreignKey, $localKey);
}
I saw I was not able to instantiate the model because model name was starting with r . lol
and i was pulling my hair since morning and another coincident was that it was like this \r so it was missing the model name and I think replacing \r with blank space and due to that the url was becoming like this
\App\Models\AddOn\Red edModel
and actual was this
\App\Models\AddOn\Red\redModel
I think it's a bug in Laravel framework.

Change "\App\Models\AddOn\Red\redModel" to:
"\App\Models\AddOn\Red\\redModel"
i.e. the extra \ will escape the \r. \r is a control character, which is why you're getting an issue.

Related

Laravel8.x - Getting exception while accessing belongsTo relationship

I have a model class created in my laravel 8.x application with the code as given below
class City extends Model
{
use HasFactory;
protected $table = 'portal_cities';
public function belongsTo()
{
return $this->belongsTo(State::class); // also tried giving 'state_id' as second parameter
}
}
I have the portal_cities table as below
When i am trying to access the following code
$eventobj = App\Models\Event::find(1);
echo $eventobj->location->city->name;
It is giving the following error
Declaration of App\Models\City::belongsTo() should be compatible with Illuminate\Database\Eloquent\Model::belongsTo($related, $foreignKey = NULL, $ownerKey = NULL, $relation = NULL)
Can you please tell me what is causing the error and what can be done to rectify it?
change relation method name
for example:
public function state()
{
return $this->belongsTo(State::class); // also tried giving 'state_id' as second parameter
}
you can't create belongsTo() function as it is core function in model
so you need to change this
class City extends Model
{
use HasFactory;
protected $table = 'portal_cities';
public function state() // change this name
{
return $this->belongsTo(State::class);
}
}
you can check core function here
https://github.com/laravel/framework/blob/8.x/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php#L193

Laravel exception: Creating default object from empty value

I'm getting this error just by instantiating a Model and setting a property.
$order_datail = new OrderDetail;
$order_detail->quantity = $product['quantity'];
I'm searching for hours for the cause of this problem but can't find it.
The constructor of OrderDetail is executed. table is order_details, but even by setting protected $table = 'order_details', I'm still getting this error. And yes there is a column 'quantity' in this table.
Strange thing is that I've no problem with other models.
$order = new Order;
$order->pickup_date = $request['date'];
$order->pickup_time = $request['pickupTime'];
The above code runs fine.
Model OrderDetail:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class OrderDetail extends Model
{
use SoftDeletes;
public function replaceds()
{
return $this->hasMany('App\Models\Replaced');
}
public function orders()
{
return $this->belongsTo('App\Models\Order');
}
public function products()
{
return $this->hasMany('App\Models\Product');
}
public function collis()
{
return $this->hasMany('App\Models\Colli');
}
}
Anyone that knows what can be the cause of this?
There is a spelling error on $order_datail = new OrderDetail;
Change it to: $order_detail = new OrderDetail;

Laravel - how to makeVisible an attribute in a Laravel relation?

I use in my model code to get a relation
class User extends Authenticatable
{
// ...
public function extensions()
{
return $this->belongsToMany(Extension::class, 'v_extension_users', 'user_uuid', 'extension_uuid');
}
// ...
}
The Extension has field password hidden.
class Extension extends Model
{
// ...
protected $hidden = [
'password',
];
// ...
}
Under some circumstances I want to makeVisible the password field.
How can I achieve this?
->makeVisible([...]) should work:
$model = \Model::first();
$model->makeVisible(['password']);
$models = \Model::get();
$models = $models->each(function ($i, $k) {
$i->makeVisible(['password']);
});
// belongs to many / has many
$related = $parent->relation->each(function ($i, $k) {
$i->makeVisible(['password']);
});
// belongs to many / has many - with loading
$related = $parent->relation()->get()->each(function ($i, $k) {
$i->makeVisible(['password']);
});
Well, I got the idea from https://stackoverflow.com/a/38297876/518704
Since my relation model Extension::class is called by name in my code return $this->belongsToMany(Extension::class,... I cannot even pass parameter to it's constructor.
So to pass something to the constructor I may use static class variables.
So in my Extension model I add static variables and run makeVisible method.
Later I destruct the variables to be sure next calls and instances use default model settings.
I moved this to a trait, but here I show at my model example.
class Extension extends Model
{
public static $staticMakeVisible;
public function __construct($attributes = array())
{
parent::__construct($attributes);
if (isset(self::$staticMakeVisible)){
$this->makeVisible(self::$staticMakeVisible);
}
}
.....
public function __destruct()
{
self::$staticMakeVisible = null;
}
}
And in my relation I use something like this
class User extends Authenticatable
{
...
public function extensions()
{
$class = Extension::class;
$class::$staticMakeVisible = ['password'];
return $this->belongsToMany(Extension::class, 'v_extension_users', 'user_uuid', 'extension_uuid');
}
...
}
The highest voted answer didn't seem to work for me (the relations attribute seems to be a protected array now so can't be used as a collection in #DevK's answer), I instead used:
$parent->setRelation('child', $parent->child->first()->setVisible(['id']));

Laravel4 - Saving a model with multiple relationships/foreign keys

I've tried to understand a process of saving a model with multiple relationships but I still can't figure out how to do it "kosher" way.
To begin with - I have an Event model that belongs to a category (Eventcat) and a Location:
// Event.php
class Event extends Eloquent {
protected $table = 'events';
public function location()
{
return $this->belongsTo('Location');
}
public function eventcat()
{
return $this->belongsTo('Eventcat');
}
public function users()
{
return $this->belongsToMany('User');
}
}
// Location.php
class Location extends Eloquent
{
protected $table = 'locations';
public function events()
{
return $this->hasMany('Event');
}
}
// Eventcat.php
class Eventcat extends Eloquent
{
protected $table = 'eventcats';
public function events()
{
return $this->hasMany('Event');
}
}
I've seeded the database with a few categories and locations and now I trying to get events saving work. I thought that the $event->eventcat()->associate( $eventcat ) would work but I got a Call to undefined method eventcat() error.
public function postCreateEvent() {
$event = new Event();
$eventcat = Eventcat::find( Input::get('event-create-eventcat[]') );
$location = Location::find( Input::get('event-create-location[]') );
$event->title = Input::get('event-create-title');
$event->description = Input::get('event-create-description');
$event->price = Input::get('event-create-price');
$event->start_date = Input::get('event-create-start_date');
$event->end_date = Input::get('event-create-end_date');
$event->eventcat()->associate( $eventcat );
$event->location()->associate( $location );
$event->save();
}
I've read the documentation, API and a few threads here but I still can't figure out the best way to deal with this.
Thanks for replies!
I would actually bet that you have a conflict in your class name. Laravel contains an Event class and I wonder if that isn't what's being called in your code. As a quick test, you could rename your class FooEvent and see if it works.
The best solution is probably namespacing your model (see http://chrishayes.ca/blog/code/laravel-4-methods-staying-organized for a quick intro) so that your model can still be called Event without conflicting with the builtin class.

Laravel Saving A Model And Relationships

I have the following Model:
class Movie extends Eloquent {
protected $primaryKey = "movie_id";
public function detail()
{
return $this->hasOne('Detail');
}
public function firstpage()
{
return $this->hasOne('Firstpage');
}
public function country()
{
return $this->belongsToMany('Countries','movies_countries','movie_id','country_id');
}
public function year()
{
return $this->hasOne('Years');
}
public function media() {
return $this->hasMany('Media');
}
}
This is the Model of interest:
class Years extends Eloquent {
protected $table = 'movies_years';
protected $primaryKey = "relation_id";
public function movie()
{
return $this->belongsTo('Movie');
}
The DBTable for years has a field "movie_year" and "movie_id"
So, I have following problem, or understanding issue:
I'm trying to update the Model Years with new Data, but can't seem the get it done. I tried the following:
$movies = Movie::find($tmp['movie_id']);
$movies->title = $tmp['title'];
$movies->title_product = $tmp['title_product'];
$movies->title_orginal = $tmp['title_original'];
$movies->year = array('movie_year' => $tmp['movieyears']);
$movies->push();
The eye is on the $movies->year row, everything else works fine.
I also tried something stupid like:
$movies->year() = array('movie_year' => $tmp['movieyears']);
I don't know how to update the Years Model, which has a relation with the Movie Model.
The offical way would be using attach, sync or associate methods. These methods are described at http://laravel.com/docs/eloquent-relationships#inserting-related-models
In your case, you'd have to do something like this:
$movies->year()->attach($tmp['movieyears']);
To remove the relation (not the Movie or Year), use detach().

Resources