Laravel Eloquent create null field - laravel

class Product extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
public $timestamps = true;
protected $fillable = ['name'];
protected $connection = 'pos';
public function __construct()
{
config(['database.connections.pos.database' => 'pos_1']);
parent::__construct();
}
}
Product::create(['name' => 'Snack']);
on my db id=1, name=null, created_at='2016-06-26 18:30:24', updated_at='2016-06-26 18:30:24', deleted_at=null
Why name=null?
Update post
works when I use
$p = new Product();
$p->name = 'Snack';
$p->save();
but why Product::create(['name' => 'Snack']); fill as null ?
Update post(solved)
ah I missing pass array as parameter on that constructor.
public function __construct(array $attributes)
{
config(['database.connections.pos.database' => 'pos_1']);
parent::__construct($attributes);
}

Probably the reason is that you again don't run parent constructor.
Instead of:
public function __construct()
{
config(['database.connections.pos.database' => 'pos_1']);
}
you should use:
public function __construct()
{
config(['database.connections.pos.database' => 'pos_1']);
parent::__construct();
}
Be aware that for your Eloquent Model you have also connection property, so you could probably set also name of database connection.

Related

laravel update() is not working on some models

I am trying to update the database record but Laravel update() function is not working. I have fillable array in the model. but still, it is not working.
The Property Model:
class Property extends Model
{
use HasFactory;
protected $table = 'properties';
protected $primaryKey = 'proID';
public $timestamps = false;
protected $fillable = [ 'proID', 'ProStatus', 'ProPurpose', 'ProType', 'SubType', 'basePrice', 'unitPrice', 'Width', 'Length', 'LandArea','PropertyNumber', 'water', 'electricity', 'gas', 'severage', 'fk_Street', 'createdBy', 'delete'];
public function streets(){
return $this->belongsTo(Street::class,'fk_Street');
}
public function hasInstallments(){
return $this->hasMany(Installments::class,'proID');
}
The PropertyController:
public function destroy($id)
{
$property = Property::find($id);
$property->delete = true;
if($property->save()){
return response()->json(['success'=>true]);
}
}
the $property->update() always returns true but record does not update in database.
The method update() is for mass update wich require an array of attributes and bypass mutators.
public function destroy($id)
{
$property = Property::find($id);
$property->update(['delete' => 1]);
}
You might want to use save() instead
public function destroy($id)
{
$property = Property::find($id);
$property->delete = 1;
$property->save();
}
Both will update the record, you'll need to implement your method's return logic on top of this code but as for updating the record, I think you get the idea.
Your property table primary key is "proID"
public function destroy($id)
{
$property = Property::where('proID', $id)->first();
if($property->update(['delete' => 1])) {
return response()->json(['success' => true]);
}
}

Trying to get property 'max_rating' of non-object in Laravel

I have these three models in Laravel-5.8
GoalType
class GoalType extends Model
{
protected $table = 'goal_types';
protected $fillable = [
'id',
'name',
];
public function goals()
{
return $this->hasMany('App\Models\Goal');
}
public function ratinglimit()
{
return $this->belongsTo(App\Models\RatingLimit);
}
}
RatingLimit
class RatingLimit extends Model
{
protected $table = 'rating_limits';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'max_rating',
];
public function goaltype()
{
return $this->hasOne('App\Models\GoalType','goal_type_id','id');
}
}
Goal
class Goal extends Model
{
protected $table = 'goals';
protected $fillable = [
'id',
'goal_type_id',
'goal_title',
];
public function goaltype()
{
return $this->belongsTo('App\Models\GoalType','goal_type_id');
}
}
Controller
$goals = Goal::where('is_approved', 3)->get();
A RatingLimit is associated with one GoalType (hasOne) and GoalType has many Goal
When I tried to render max_rating
index.blade
{{$goal->goaltype->ratinglimit->max_rating}}
I got this error:
Trying to get property 'max_rating' of non-object
When I changed it to:
{{ $goal->goaltype->ratinglimit ? $goal->goaltype->ratinglimit->max_rating : '-' }}
it deisplays '-', and the error is no more there. But max_rating in the database is not empty
How do I resolve this?
Thanks
->get() returns a collection! so you should loop it through foreach to have access to each item and then you can use your relation:
#foreach ($goals as $g)
{{$goal->goaltype->ratinglimit->max_rating}}
#endforeach

storing and updating has-many relationships laravel

i m about storing datas using haMany Relatiions
where Cars may have more than picture
and each picture can have only one car
Car Modem Car.php
class Car extends Model
{
protected $table = 'cars';
public $timestamps = true;
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = array('Marque', 'Model', 'sieges', 'climatisation', 'portes', 'transmition', 'price','url','car_id');
public function cars_images()
{
return $this->hasMany(CarsImage::class);
}
CarsImage Model
class CarsImage extends Model
{
protected $table = 'cars_images';
public $timestamps = true;
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = array('url');
public function cars()
{
return $this->belongsTo(Car::class);
}
}
MyController :
public function store(Request $request) {
$car = new Car;
$car->Marque = Input::get('Marque');
$car->Model = Input::get('Model');
$car->sieges = Input::get('sieges');
$car->climatisation = Input::get('climatisation');
$car->portes = Input::get('portes');
$car->transmition = Input::get('transmition');
$car->price = Input::get('price');
$img = new CarsImage;
$img->url = 'jean Luc Picard';
DB::transaction(function() use ($car, $img) {
$car = $car->save();
Car::find($car->id)->cars_images()->save($img);
});
return 'ok';
}
the problem is the car is saved and the url also is saved but with not the car_id
Any help please ?
just use create method:
$car = Car::create([
'Marque' => $request->Marque,
//other fields...
]);
$image = $car->cars_images()->create([
'url' => 'jean Luc Picard'
]);
and don't forget to use $fillable in your models.

laravel eloquent doesn't use protected table name

In my model i added protected $table, but when i'm going to use it laravel does't use it. This is my role models:
class Role extends Model
{
protected $table = 'role';
protected $primaryKey = 'ROLE_ID';
protected $casts = [
'ACTIVE' => 'boolean',
];
protected $fillable = [
'ROLE', 'ACTIVE', 'TYPE'
];
public $timestamps = false;
public function groups()
{
return $this->belongsToMany(Group::class, GroupRole::class, 'ROLE_ID', 'GROUP_ID');
}
}
And this is Group model:
class Group extends Model
{
protected $table = 'groups';
protected $primaryKey = 'GROUP_ID';
protected $fillable = [
'GROUP_ID', 'GROUP_NAME', 'PARENT_GROUP', 'ACTIVE'
];
protected $casts = [
'ACTIVE' => 'boolean',
];
public $timestamps = false;
public function type()
{
return $this->belongsTo(GroupType::class, 'TYPE', 'TYPE_ID');
}
public function roles()
{
return $this->belongsToMany(Role::class, GroupRole::class, 'GROUP_ID', 'ROLE_ID');
}
}
And this is group_role table model. It handles many to many relation between role and group:
class GroupRole extends Model
{
protected $table = 'group_role';
protected $primaryKey = 'GROUP_ROLE_ID';
protected $fillable = [
'COMMENT', 'ROLE_ID', 'GROUP_ID'
];
public $timestamps = false;
}
Problem begin when i want to use this models. For example:
$role = App\Role::first();
$groups = $role->groups;
Laravel returns this error messages:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'favian_mydb.App\GroupRole' doesn't exist (SQL: select groups.*, App\GroupRole.ROLE_ID as pivot_ROLE_ID, App\GroupRole.GROUP_ID as pivot_GROUP_ID from groups inner join App\GroupRole on groups.GROUP_ID = App\GroupRole.GROUP_ID where App\GroupRole.ROLE_ID = 1)
I tried to replace App\GroupRole with group_role and executing in mysql. It works fine. Am i missing something?
The Problem is in your roles relation:
public function roles()
{
return $this->belongsToMany(Role::class, GroupRole::class,'GROUP_ID','ROLE_ID');
}
The belongsToMany expects the intermediate table name as second argument, not the class name.
So you have to define it like this:
public function roles()
{
return $this->belongsToMany(Role::class, 'group_role','GROUP_ID','ROLE_ID');
}
I think the problem is in you relation functions. Try to use strings instead of Model::class.
Example:
return $this->return $this->belongsTo('App\GroupType', 'TYPE', 'TYPE_ID');
Hope this works.

How to use "select" method to reduce data transfer when using Eager Loading

I have a API and its taking long time to get all the info and its because I'm only hidding some data but I want to omit not to hidde. I found select() method to chose wich data send and reduce the time to query all information I really need.
Im trying to use select just after the relation just like this, just to retrieve only name from OPR_User table:
public function creatorUser() {
return $this->belongsTo('Knotion\OPR_User', 'idCreatorUser', 'idUser')->select('name');
}
but is not working
This is my Model code
<?php
namespace Knotion;
use Illuminate\Database\Eloquent\Model;
class CTL_Resource extends Model {
protected $table = "CTL_Resource";
protected $primaryKey = "idResource";
public $incrementing = false;
public $timestamps = false;
public static $snakeAttributes = false;
protected $hidden = [
'coachVisibility', 'thumbnail',
'studentVisibility', 'isHTML','studentIndex', 'coachIndex',
'isURL', 'source', 'path', 'status', 'updateTime', 'isfolder',
'parentResource', 'idModifierUser', 'idResourceType', 'idCreatorUser', 'idCreationCountry'
];
protected $fillable = ['idResourceType','productionKey', 'idCreatorUser', 'idModifierUser', 'idCreationCountry', 'title', 'description', 'URL', 'fileName', 'extension', 'minimumAge', 'maximumAge', 'productionKey'];
public function creatorUser() {
return $this->belongsTo('Knotion\OPR_User', 'idCreatorUser', 'idUser');
}
public function creationCountry() {
return $this->belongsTo('Knotion\CTL_Country', 'idCreationCountry', 'idCountry');
}
public function resourceType() {
return $this->belongsTo('Knotion\CTL_ResourceType', 'idResourceType', 'idResourceType');
}
public function quickTags() {
return $this->belongsToMany('Knotion\CTL_QuickTag', 'CTL_Resource_has_QuickTags', 'idResource','idQuickTag');
}
public function tags() {
return $this->belongsToMany('Knotion\CTL_Tag','CTL_Resource_has_Tags', 'idResource', 'idTag');
}
public function relatedTo() {
return $this->belongsToMany('Knotion\CTL_RelatedTo', 'CTL_Resource_has_RelatedTo', 'idResource', 'idRelatedTo');
}
}
this is my relation model code (just in case needed):
<?php
namespace Knotion;
use Illuminate\Database\Eloquent\Model;
class OPR_User extends Model {
protected $table = "OPR_User";
protected $primaryKey = "idUser";
public $incrementing = false;
public $timestamps = false;
public static $snakeAttributes = false;
protected $hidden = ['firstName', 'secondName', 'firstSurName', 'secondSurName', 'password', 'picture', 'status', 'createTime', 'updateTime', 'idUserType', 'email'];
public function resources() {
return $this->hasMany('Knotion\CTL_Resource', 'idResource');
}
public function userType() {
return $this->belongsTo('Knotion\CTL_UserType', 'idUserType', 'idUserType');
}
}
and this is my Controller code:
public function index(Request $request) {
$resources = CTL_Resource::all();
$resources->resourceType->select('name');
return $resources->load('creatorUser', 'creationCountry', 'resourceType', 'tags', 'quickTags', 'relatedTo');
}
When you add the ->select after the ->belongsTo it's no longer an actual relationship type, it's a query builder. You need to add the select afterwards before you call the ->load.
To fix the problem I had to include the id also in the relation, something like this:
public function resources() {
return $this->hasMany('Knotion\CTL_Resource', 'idResource')->select('idResource', 'name');
}

Resources