Appending an attribute to a Laravel 7.9.2 model? - php

Here is my code:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Unit_Live extends Model
{
protected $table = 'live_data_units';
public function getUnitNameAttribute()
{
return "{$this->unitName}";
}
protected $appends = ['unit_name'];
}
Output:
If I change the $appends array, I can see default:
protected $appends = ['unit_name' => 'default'];
The expected output should be unit_a. unitName is a column in my table, value is shown under #attributes in image 1.
Docs:
https://laravel.com/docs/7.x/eloquent-serialization#appending-values-to-json

Related

Problem with Laravel Eloquent reltionships for tables without relations

I, ve got problem with eloquent relationships.
This is my DB
https://i.stack.imgur.com/2we4g.jpg
https://i.stack.imgur.com/20KeG.jpg
I've got Santander ID in santander column in partner table and want to use data from those two table like from one
This is my Partner.php model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Partner extends Model
{
use HasFactory;
protected $table='partner';
protected $connection='mysql2';
protected $guarded = [];
public $primaryKey = 'id';
public function santander()
{
return $this->hasOne(Santander::class, 'id', 'santander');
}
}
This is my Santander.php model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Santander extends Model
{
use HasFactory;
protected $table='santander';
protected $connection='mysql2';
protected $guarded = [];
public $primaryKey = 'id';
public function partner()
{
return $this->belongsTo(Partner::class, 'id', 'santander');
}
}
In controller I use Eloquent collection like this:
use App\Models\Partner;
use App\Models\Santander;
$partners = Partner::paginate(10);
In view. I am using it like this:
#foreach partners as partner
{{ $partner->santander->operator }}
#endforeach
but it generates error:
Trying to get property 'santander' of non-object
First of all are you sure about the relationships itself?
$this->hasOne(Santander::class, 'id', 'santander');
The first extra argument should be the foreign key, so assuming that the related column in the model Santander is named santander then it should be:
$this->hasOne(Santander::class, 'santander', 'id');
(the specified id as last param can be omitted btw)
Same goes for the relationship in the other model.

Illegal offset type when i create a new row on Laravel

We created three tables called 'users', 'corso', 'iscrizione' is a middle table between users and corso, it has two attributes that are PK/FK. We successfully built the methods to create/update/read/delete rows inside 'corso' and we populated manually 'users'. We are trying to realize a create method for iscrizione but when we tried to execute it with Postman it generates this error:
ErrorException: Illegal offset type in file I:\Test db Laravel\testdb\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php on line 1146
🧨 Illegal offset type
These are the Class Models of each tables on the database:
Iscrizione Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Iscrizione extends Model
{
use HasFactory;
protected $hidden = ['idCorso', 'idUtente'];
protected $primaryKey = ['idCorso', 'idUtente'];
protected $table = 'iscrizione';
}
Corso Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Corso extends Model
{
use HasFactory;
protected $primaryKey = 'idCorso';
protected $table = 'corso';
protected $fillable = ['tipo','nome', 'membriMax', 'inizio', 'fine'];
}
The last one is the creation method on our ApiController Class:
public function iscrizione(Request $request){
$iscrizione = new Iscrizione();
$iscrizione->idCorso = $request->input('idCorso');
$iscrizione->idUtente = $request->input('idUtente');
$iscrizione->save();
return response()->json($iscrizione);
}
}
You need to override the setKeysForSaveQuery to use the composite keys you have defined for the Iscrizione model:
Iscrizione.php
protected function setKeysForSaveQuery(Builder $query)
{
return $query->where('idCorso', $this->getAttribute('idCorso'))
->where('idUtente', $this->getAttribute('idUtente'));
}
and also remove the following line
protected $primaryKey = ['idCorso', 'idUtente'];

Null values instead of an Value in CodeIgniter

I have this code that is returning a NULL instead of a value. Here is my Controller with the name Agents, this code runs on the Admin side but when I used the code for Agents user levels it's returning NULL:
<?php namespace App\Controllers;
use App\Models\ClientModel;
class Agent extends BaseController{
public $modelClients;
public function __construct(){
$this->modelClients = new ClientModel();
}
function getClientsToAgent($id){
$data = ([
"title" => "Lead Generation",
"client" => $this->modelClients->where("clientsId", $id)->first(),
"tasks" => $this->modelTasks->orderby("taskId", "ASC")->findAll()
]);
echo view('agentTemplate/header',$data);
echo view('agents/loadLeadGenView');
echo view('agentTemplate/footer');
}
}
and on my view named loadLeadGenView:
<?php
var_dump($client);
?>
here's my Model name ClientModel:
<?php namespace App\Models;
use CodeIgniter\Model;
class ClientModel extends Model{
protected $table = "tblclients";
protected $primaryKey = "clientsId";
protected $returnType = 'array';
protected $allowedFields = ["clientsId","clientsFirstname","clientsMiddlename", "clientsLastname","clientsBusinessName","clientsCampaignGoals","clientsDateStarted","clientsJointVenture","clientsEmailAddress"];
}
Another this on my Routes.php:
$routes->get('agents/getClientsToAgent/(:num)', 'Agents::getClientsToAgent/($1)');
that is why I'm wondering. why it's returning NULL instead of a value?
fix your route, remove brackets around $1
$routes->get('agents/getClientsToAgent/(:num)', 'Agents::getClientsToAgent/$1');
https://codeigniter4.github.io/CodeIgniter4/incoming/routing.html#examples

How to get data for one to many relationship using Eloquent in Laravel?

How to get data for one to many relationship using Eloquent in Laravel? Actually I followed Eloquent Documentation. But my code returns me an empty array. Here's my work:
Database Schema
Parent Table: mtg_workspace with columns (mw_id[primary key], mw_name,..., mw_access)
Child Table: mtg_workspace_amenities with columns (id[primary key], wa_mwid, wa_name)
Model: MtgWorkspace.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class MtgWorkspace extends Model
{
protected $table = 'mtg_workspace';
public $timestamps = false;
public function MtgWorkspaceAmenities(){
return $this->hasMany('App\MtgWorkspaceAmenities', 'wa_mwid');
}
}
Model: MtgWorkspaceAmenities.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class MtgWorkspaceAmenities extends Model
{
protected $table = 'mtg_workspace_amenities';
public $timestamps = false;
public function MtgWorkspace(){
return $this->belongsTo('App\MtgWorkspace');
}
}
Controller: WorkspaceController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\MtgWorkspace;
use App\MtgWorkspaceAmenities;
class WorkspaceController extends Controller
{
public function index()
{
$workspace = MtgWorkspace::with('MtgWorkspaceAmenities')->get();
return $workspace;
}
}
and here it shows following output:
Can you try defining the primary key for the MtgWorkspace model (as it is not id):
protected $primaryKey = 'mw_id';
I don't think it can match up the children MtgWorkspaceAmenities to the parent MtgWorkspace models as it is trying to use the id attribute on MtgWorkspace to match to the foreign key on MtgWorkspaceAmenities when it spins through the result of the eager loading.
Side Note:
You will have to pass more parameters to the inverse relationship on MtgWorkSpaceAmenities when defining it, as belongsTo() wants to use the calling methods name snake cased with _id added if not told otherwise as the key.

Laravel - nested relationship shows null

I have a tw-tier nested hasOne relationship and the final relationship appears to be giving null values.
My JobApplication relationship has the following:
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class JobApplication extends Model
{
protected $table = 'job_applications';
protected $primaryKey = 'job_application_id';
public function jobrequest()
{
return $this->hasOne('App\Model\JobRequest', 'job_request_id', 'job_request_id');
}
}
My JobRequest Model has the following:
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class JobRequest extends Model
{
protected $table = 'job_requests';
protected $primaryKey = 'job_request_id';
public function jobgroup()
{
return $this->hasOne('App\Model\JobGroup', 'job_group_code', 'job_group_code');
}
public function jobapplication()
{
return $this->belongsTo('App\Model\JobApplication', 'job_request_id');
}
}
And my JobGroup has the following:
<?php
namespace App\Model;
use Carbon;
use Illuminate\Database\Eloquent\Model;
class JobGroup extends Model
{
protected $table = 'job_groups';
protected $primaryKey = 'job_group_code';
public function jobrequest()
{
return $this->belongsTo('App\Model\JobRequest', 'job_group_code');
}
}
I access them in my controller like so:
$job_applications = JobApplication::with(['jobrequest', 'jobrequest.jobgroup'])
->where('user_id', Auth::id())
->first();
It queries right on the Debugbar (and yes the query for job_groups gives out data), but when I dumped $job_applications, jobgroup shows null
Dont need to eager load it. I can access it like so
$job_applications = JobApplication::with('jobrequest')->where('user_id', Auth::id())->first();
dd($job_applications->jobrequest->jobgroup);

Categories