Indirect modification of overloaded on Laravel - Relationship - laravel

I use Laravel 5 and i have 2 tables:
"Link" Table with 7 columns, one of them is "image_id" column.
"Image" Table, in this table i have two column, an "id" and "url".
I want to update my Link database and also it's related image url with single update method.
I have tried this code:
public function update(Request $request, $id)
{
// Validate the data
$link = Link::find($id);
$this->validate($request, array(
'title' => 'required|max:255',
'link' => 'nullable',
'description' => 'required'
));
$link = Link::find($id);
$link->title = $request->input('title');
$link->link = $request->input('link');
$link->description = $request->input('description');
$link->linkImage->url = 'testurl';
$link->save();
Session::flash('success', "Le lien à été correctement mis à jour.");
return redirect()->route('links.index');
}
This is my Link class:
<?php
namespace App\Models\Services;
use Illuminate\Database\Eloquent\Model;
class Link extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'service_rubrique_link';
protected $fillable = ['title','description','ordre','image_id'];
public function linkImage()
{
return $this->belongsTo('App\Models\Storage\Imageup');
}
}
And my Image Class:
<?php
namespace App\Models\Storage;
use Illuminate\Database\Eloquent\Model;
class Imageup extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'image';
protected $fillable = ['id','url'];
public function servlinks()
{
return $this->hasMany('App\Models\Services\Link');
}
}
When i want to save i have this error:
Indirect modification of overloaded property
App\Models\Services\Link::$linkImage has no effect
Do you have any idea of what is wrong with my code ?
Thank you.

As the message says the property is a lazy loaded sub model.
Updating does not makevsense... you should use it as method (query builder) linkimage() and then use for example ->update(['propertyname' => 'value'])
See https://laravel.com/docs/7.x/eloquent-relationships#inserting-and-updating-related-models

Related

trying to get property 'sector' of non-object

guys. I'm trying to pass the 'officeToSector' id from employee table to get the 'sector' table values using the id. But it doesn't work, it show me 'trying to get property 'sector' of non-object'. However, if I entered a number like 1 or 2, I can access the property. I had checked the type of the return query, it is an object not an array...
Can you guys pls help me to find out what is the problem. Thank you very much.
$employees = $this->employeeRepository->listEmployees();
return Datatables::of($employees)
->addColumn('department', function($employee){
// if I assign 2 to $id, I got the return value,
// but it I use the emp->dept_id, I get the non-object error
$id = (int)$employee->department_id;
$sector = OfficeToSector::find($id);
return $sector->sector->name;
)}
->rawColumns(['department'])
->make(true);
officeToSector model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
// use Illuminate\Database\Eloquent\Relations\Pivot;
class OfficeToSector extends Model
{
protected $table = 'office_to_sectors';
/**
* #var array
*/
protected $fillable = ['office_id','sector_id'];
public function office()
{
return $this->belongsTo(Office::class, 'office_id', 'id');
}
public function sector()
{
return $this->belongsTo(Sector::class, 'sector_id');
}
public function employee()
{
return $this->hasMany(Employee::class, 'employee_id', 'id');
}
public function registeredDepartment()
{
return $this->hasOne(DepartmentContent::class, 'department_id');
}
}
sector model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Sector extends Model
{
/**
* #var array
*/
protected $fillable = ['name','status'];
/**
* #var array
*/
protected $casts = [
'status' => 'boolean',
];
public function offices()
{
return $this->belongsToMany('App\Models\Office', 'office_to_sectors')->withPivot('sector_id', 'office_id')->withTimestamps();
}
}
I found the solution. It is because one of the sector value in the officeToSector table is null. So, this is why Yajra Datatable cannot display the data because the table has null value.

Get specific columns having with() function in laravel

Category Model definition is:
class Category extends Model
{
public $implement = ['#RainLab.Translate.Behaviors.TranslatableModel'];
public $translatable = ['name'];
/**
* #var string The database table used by the model.
*/
public $table = 'shop_category';
/**
* #var array Validation rules
*/
public $rules = [
];
public $attachOne = [
'icon' => 'System\Models\File'
];
public $hasMany =[
'shops' => ['ItScholarBd\Api\Models\Shop', 'key' => 'shop_category_id']
];
}
I want to get category with shop. It works fine if I retrieve all columns but if I try to retrieve specific column it is not working. I want to get only the following columns:
id, name of each table. I also apply a condition where Shop.status = 1. I am trying as follows:
$this['categoryWithShop'] = Category::select('id,name')->with(array('shops'=>function($query){
$query->where('status','=',0);
$query->select('id','name');
}))->get();
Any idea?
Try this,
$this['categoryWithShop'] = Category::select('id,name')->with(array('shops'=>function($query){
$query->where('status','=',0);
$query->select('id','name', 'status');
}))->get();
In select query you need to pass that all columns which is needed in query.
try this chaining method and select('id,name') this is wrong you need to fix this as select('id','name')
ref link https://laravel.com/docs/8.x/queries#selects
$this['categoryWithShop'] = Category::select('id','name')->with(['shops' => function ($query) {
$query->select('id', 'name')->where('status', '=', 0);
}])->get();

Problem relationship many to many on Laravel

I'm new to Laravel, I'm having this problem:
I have 2 tables, platos and ingredientes, these have a many to many relationship, and for this I use a third table called ingredientes_platos.
To save the relationship many to many I tried with the following:
$platos->ingredientes()->attach($input['ingredientes']);
but it gives the following error:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '151-3' for key 'PRIMARY' (SQL: insert into ingredientes_platos (platos_id, ingredientes_id, norma_bruta) values (151, 3, ))
Looking a bit in the documentation, I could solve with sync instead of attach, but this does not solve my problem, because in addition to saving the id's of the relationship I need to save other attributes in the pivot table.
It is important to note that if I try to save this data in a table other than ingredients_platos, I do not get this problem and the data is saved correctly no matter which method I use.
I appreciate your attention, I hope you can help me.
These are the models for the three tables:
Table Platos:
public $table = 'platos';
protected $dates = ['deleted_at'];
public $fillable = [
'Grupo',
'Nombre',
'Procedimiento',
'Cantidad',
'Unidad',
'Precio'
];
/**
* The attributes that should be casted to native types.
*
* #var array
*/
protected $casts = [
'Grupo' => 'integer',
'Nombre' => 'string',
'Procedimiento' => 'string',
'Cantidad' => 'integer',
'Unidad' => 'integer',
'Precio' => 'double'
];
/**
* Validation rules
*
* #var array
*/
public static $rules = [
'Grupo' => 'required',
'Nombre' => 'required'
];
public function ingredientes()
{
return $this->belongsToMany(Ingredientes::class);
}
public function grupo_platos()
{
return $this->hasOne('App\Models\Grupo_Platos', 'id', 'Grupo');
}
}
Table Ingredientes:
public $table = 'ingredientes';
protected $dates = ['deleted_at'];
public $fillable = [
'Grupo',
'Nombre',
'Descripcion',
'Kcal',
'Proteinas',
'Grasas',
'Unidad',
'Precio'
];
/**
* The attributes that should be casted to native types.
*
* #var array
*/
protected $casts = [
'Grupo' => 'integer',
'Nombre' => 'string',
'Descripcion' => 'string',
'Kcal' => 'double',
'Proteinas' => 'double',
'Grasas' => 'double',
'Unidad' => 'integer',
'Precio' => 'double'
];
/**
* Validation rules
*
* #var array
*/
public static $rules = [
'Nombre' => 'required'
];
public function platos()
{
return $this->belongsToMany(Platos::class);
}
}
Table Ingredientes_Platos:
public $table = 'ingredientes_platos';
public $fillable = [
'platos_id',
'ingredientes_id',
'norma_bruta',
'norma_neta',
'unidad_id'
];
public $timestamps = false;
}
Platos Controller:
public function store(CreatePlatosRequest $request)
{
$input = $request->all();
$platos = $this->platosRepository->create($input);
$id = $platos->id;
$ingredientes = $input['ingredientes'];
$norma_b = $input['norma_b'];
$t = sizeof($ingredientes);
$i=0;
for ($i = 0; $i < $t; $i++) {
$pivot = new Ingredientes_Platos;
$pivot->platos_id = $platos['id'];
$pivot->ingredientes_id = $ingredientes[$i];
$pivot->norma_bruta = $norma_b[$i];
$pivot->save();
}
Flash::success('Plato agregado correctamente.');
return redirect(route('platos.index'));
}
If you need one type to "belong" to another type multiple times, and vice versa, then the generic many-to-many relationship probably isn't a good fit for what you're trying to do. Not just because of the primary key constraint, but because you'll have cases in which multiple row results are returned for the relationship, and the many-to-many relationship won't know how to aggregate or group these. You may want to come up with a third type of Model that's something like an "attribute" that has relationships to the other two models and helps you accomplish your goal.
Thank you very much, my problem was solved. It happens that in addition to Laravel, I'm using InfyOM and this was creating a conflict when I was trying to manually add the records to the pivot table, because this line was already responsible for adding the registry to the pivot table: $ dishes = $ this-> dishesRepository-> create ($ input);
// Many to Many relationship in category Model to Post model coding here
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function posts()
{
return $this->belongsToMany('App\Post')->withTimestamps();
}
}
// Many to Many relationship in Post Model to Category model coding here
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function categories(){
return $this->belongsToMany('App\Category')->withTimestamps();
}
}

How to make dynamic query in laravel 5 with model and controller

i have Add query in codeigniter like this:
in controller:
$data=array(
'table'=>'tbl_activity_log',
'val'=>array(
'x'=>$x,
'y'=>$y,
'z'=>$z,
));
$log=$this->model->add_data($data);
And in model add_data function like this:
function add_data($data)
{
return $this->db->insert($data['table'],$this->security->xss_clean($data['val']));
}
But In Laravel 5 I have:
$name=$Request->input('name');
$lname=$Request->input('lname');
$myItems = array(
'first_name'=>$name,
'last_name'=>$lname
);
DB::table("tbl_user")->insert($myItems);
My question is, how can we make table field dynamic in Laravel and call that function through model.
Also, how can I call that function from model? Any help please. I want a dynamic query
You can write a helper function
//create a helper function
function addModelData($arrayData = [])
{
return \DB::table($arrayData['table'])->insert($arrayData['val']));
}
//in your controller or any place you like
$data=array(
'table'=>'tbl_activity_log',
'val'=>array(
'x'=>$x,
'y'=>$y,
'z'=>$z,
));
$log = addModelData($data);
You could create a model as described in official documentation:
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'tbl_user';
// If your primary key is not 'id'
protected $primaryKey = 'model_id';
}
Now in your controller you can use this model:
namespace App\Http\Controller;
use App\User;
use Illuminate\Http\Request;
class MyController extends Controller {
public function myAction(Request $request){
$user = new User();
$user->last_name = $request->input('lname');
$user->first_name = $request->input('name');
$user->save();
}
}
You also could use mass assignment. But before you have to set the $fillable attribute in your model:
protected $fillable = ['first_name', 'last_name'];
Now you can use mass assignment in your controller:
$user = User::create([
'first_name' => $request->input('name'),
'last_name' => $request->input('lname')
]);
// alternatively:
$user = User::create($request->only(['name', 'lname']));

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db.store' doesn't exist

When I try to save data from laravel form to a database table I am getting the following exception:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db.store' doesn't exist (SQL: select count(*) as aggregate from store where name = samplename)
the table store exists but still I am getting the error
this is my contoller that is processing the form:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\storestore;
use App\Http\Requests\storeFormRequest;
class AddstoreController extends Controller
{
//
public function create()
{
//
}
public function store( storeFormRequest $request)
{
$store = new Store;
$store->name = Input::get('name');
$store->description = Input::get('description');
$store->store_vendor_id = Input::get('owner');
$store->contact_email = Input::get('contact_email');
$store->postal_address = Input::get('postal_address');
$store->city = Input::get('city');
$store->zip = Input::get('zip');
$store->phone = Input::get('phone');
$store->business_logo = Input::get('logo');
$store->save();
return \Redirect::route('add_store_success')
->with('message', 'Thanks for joining us!');
}
}
This is my Store model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Store extends Model
{
//
protected $table = 'stores';
protected $fillable = ['name', 'description', 'vendor_id',
'contact_email','postal_address','city','zip','phone',
'meta_description','business_logo'];
}
StoreRequest file:
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use App\StoreController;
class StoreFormRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
//
'name' => 'required|unique:dstore',
'vendor_id' => 'required',
'contact_email' => 'required|email|max:100|unique:dstore',
'business_logo' => 'required',
];
//validate
if ($validation->fails())
{
return redirect()->back()->withErrors($v->errors());
}
}
}
These are the get and post routes:
Route::get('/store_form', ['as' => 'add_store_form', 'uses' => 'StoreController#create']);
Route::post('/store_form',['as' => 'dstore', 'uses' => 'StoreController#store']);
Both routes are listed when I run php artisan route:list command
I have tried to goggle for solution but the one I landed on pointed out to missing tables as a course, but in my case the store table is existing but still I am getting the error.
Any help please!
Look at your Store model class:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Store extends Model
{
//
protected $table = 'stores';
protected $fillable = ['name', 'description', 'vendor_id',
'contact_email','postal_address','city','zip','phone',
'meta_description','business_logo'];
}
As you see property $table is set to stores so I assume table name in your database is stores and not store.
You should probably change in your StoreFormRequest content or rules method to use in unique rule valid table name, for example:
public function rules()
{
return [
//
'name' => 'required|unique:stores',
'vendor_id' => 'required',
'contact_email' => 'required|email|max:100|unique:stores',
'business_logo' => 'required',
];
//validate
if ($validation->fails())
{
return redirect()->back()->withErrors($v->errors());
}
}

Resources