Property [client] does not exist on this collection instance - sql

I can't get the value of the foreign key that is inside the booking table.
Booking Table
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class booking extends Model
{
protected $primaryKey = 'bookingID';
protected $fillable = ['clientID', 'checkInDate', 'checkOutDate', 'roomsCount', 'roomTypeID', 'adultsCount', 'childrenCount', 'amenityID', 'paymentID'];
public function client()
{
return $this->hasOne(Client::class,'clientID');
}
}
Client Table
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class client extends Model
{
protected $primaryKey = 'clientID';
protected $fillable = ['fullNmae', 'firstName', 'lastName', 'phoneNumber', 'emailAddress'];
public function booking()
{
return $this->hasMany(Booking::class);
}
}
I tried adding the protected $primaryKey = 'bookingID'; and protected $primaryKey = 'clientID'; as suggested in my previous question but now I still can't get just the FirstName from the client table.
$bookingDetail = booking::with('client')->get();
return $bookingDetail->client->firstName;

You are trying to get a property from a collection in these lines:
$bookingDetail = booking::with('client')->get();
return $bookingDetail->client->firstName;
but this property client is defined for object, not a collection. so to solve it you must take one object from the collection like the following:
$bookingDetail = booking::with('client')->first();
return $bookingDetail->client->firstName;

i thing you need to try this one:
in your booking model:
// 'App\Client' these is example you need to put your client model path
public function client()
{
return $this->belongsTo('App\Client','clientID');
}
in your client model:
public function booking()
{
return $this->hasMany('App\Booking' , 'clientID');
}

Related

Associate method in laravel 8

I'm new to laravel and I'm making a small api with just two tables to start. I have roles and people. I want to assign a role to a person from the store method but I don't understand how associate() works or how to implement it in the store method, this is what i have;
Model Rol:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
use HasFactory;
protected $fillable = ['id', 'rol'];
public function personas()
{
return $this->hasMany(Persona::class);
}
}
Model Persona:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Role;
class Persona extends Model
{
use HasFactory;
protected $fillable = ['id', 'nombres', 'apellidos', 'rol_id'];
public function rol()
{
return $this->belongsTo(Role::class, 'rol_id');
}
}
$rol = Role::find(1);
$persona->rol()->associate($rol);
$persona->save();
Persona controller store method:
public function index()
{
return PersonaResource::collection(Persona::with('rol')->paginate(25));
}
public function store(Request $request)
{
//$rol = Role::find(1);
$persona = new Persona();
// datos que voy a guardar
$persona->nombres = $request->nombres;
$persona->apellidos = $request->apellidos;
$rol = new Role();
//$rol->personas()->save($rol);
$persona->rol()->save($rol);
}
I want to know how to correctly associate both models to be able to correctly save the related data

Using foreign key in controllers Laravel 9

I was creating two tables user and user_info and i want to use the userid in userinfo.
I don't know how to use the userid in userinfocontroller.
You must define one to one relation in your models.
in User Model :
public function info()
{
return $this->hasOne(Info::class,'foreign key'); // (Info = your userinfo model)
}
and in your Info model :
public function user()
{
return $this->belongsTo(User::class, 'foreign key');
}
you can read documents too.
In the User Model
public function info()
{
return $this->hasOne(userinfo::class);
}
And in userinfo Model
public function user()
{
return $this->belongsTo(User::class);
'user_id'
}

Laravel: How to send value from Controller to Model?

How can I send a value from Controller to Model and how to receive the value in the Model.
I let above a picture of my database tables.
enter image description here
Example: If I enter in the input 3 action movies
$category=category::with('film')->where('name','=','Action')->first();
Film model:3
class film extends Model{
protected $table = "film"; //Para nao dar o erro de singular e plural
protected $primaryKey = 'film_id';
public $timestamps = false;
use HasFactory;
protected $sql=['film_id', 'title', 'release_year'];
public function category(){
return $this->belongsToMany(category::class,'film_category', 'film_id', 'category_id');
}
}
Category model:
class category extends Model{
protected $table = "category";
protected $primaryKey = 'category_id';
public $timestamps = false;
use HasFactory;
protected $sql=['category_id','name'];
public function film(){
return $this->belongsToMany(film::class,'film_category', 'category_id', 'film_id');
}
}
NOTE: I realized that I need to add in the front of the Category model
->take(3)
But I don't know how to send the value(3 or other else) via $category query.
You can simply put conditions in the closure of the "film" relationship on the controller to get 3 action movies or any number of movies.
Controller:
$limit = 3;
$category=category::with(['film'=>function($query)use($limit)
{
$query->limit($limt);
}])->where('name','=','Action')->first();
Controller Side
$category=category::with('film')->where('name','=','Action')->film->category($value);
Model Side
public function category($value){
return $this->belongsToMany(category::class,'film_category', 'film_id', 'category_id')->where('foo', $value);
}

Yii2 REST create with fields()

Let's say that I had the following API set up:
Controller:
<?php
namespace app\modules\v1\controllers;
use yii;
class ResourceController extends \yii\rest\ActiveController
{
public $modelClass = 'app\modules\v1\models\Resource';
}
Model:
use yii;
class Resource extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'ResourceTable';
}
public function fields()
{
return [
'id' => 'ResourceID',
'title' => 'ResourceTitle',
];
}
}
where my table only has the two columns, ResourceID and Title.
When I try a GET request on the API, it works fine and returns the list of resources (or single resource in the case of resource/{id}) with the aliased field names. But when I try to POST to create a resource, I want to use the aliased field names (e.g. title instead of ResourceTitle). The problem is that the default CreateAction supplied by Yii does $model->load(), which looks for the field names in the table. If I use the aliased names then it returns an error. If I use the table field names, it works fine.
So my question is, is there a way to expose resource attributes to the end user where the field names (using the fields() function) are the same for reading and creating? If possible, I'd like to avoid writing my own CreateAction.
It's necessary to add rules for new virtual properties, if you want to $model-load() save parameters to them
class OrganizationBranch extends BaseOrganization{
public function rules()
{
return array_replace_recursive(parent::rules(),
[
[['organizationId', 'cityId'], 'safe'],
]);
}
public function fields() {
return ['id',
'cityId' => 'city_id',
'organizationId' => 'organization_id',
'address',
'phoneNumbers' => 'phone_numbers',
'schedule',
'latitude',
'longitude',
];
}
public function extraFields() {
return ['branchType', 'city'];
}
public function getOrganizationId() {
return $this->organization_id;
}
public function setOrganizationId($val) {
$this->organization_id = $val;
}
public function getCityId() {
return $this->city_id;
}
public function setCityId($val) {
$this->city_id = $val;
}
}
You can create getters/setters for alias.
public function getTitle(){ return $this->ResourceTitle; }
public function setTitle($val){ $this->ResourceTitle = $val ; }

Please explain the foreign_key and local_key in Laravel ORM relationships

I'm effectively trying to define the relationships between users (sender and recipient) and messages.
My Messages migration is:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMessagesTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
//
Schema::create('messages', function($t){
$t->increments('id');
$t->integer('sender_user_id')->unsigned();
$t->integer('recipient_user_id')->unsigned();
$t->string('subject');
$t->text('content');
$t->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
Schema::dropIfExists('messages');
}
}
My Message model was straightforward:
<?php
class Message extends Eloquent{
// link to sender user id
public function from(){
return $this->hasOne('User', 'sender_user_id');
}
// link to recipient user id
public function to(){
return $this->hasOne('User', 'recipient_user_id');
}
}
But I'm unsure in defining the hasMany relationships in my User model.
The docs (http://laravel.com/docs/eloquent#relationships) shows the following:
return $this->hasMany('Comment', 'foreign_key');
return $this->hasMany('Comment', 'foreign_key', 'local_key');
Now, I'm confused which key is which in the latter hasMany relationship. Which is correct for my User model?
public function sentMessages(){
return $this->hasMany('Messages', 'id', 'sender_user_id');
}
public function sentMessages(){
return $this->hasMany('Messages', 'sender_user_id', 'id');
}
You have to set your relation like this:
public function sentMessages()
{
return $this->hasMany('Messages', 'sender_user_id');
}
public function receivedMessages()
{
return $this->hasMany('Messages', 'recipient_user_id');
}