laravel relationships beetween table foreign key - php

I have a problem. I want to create a dropdown box with the name's from a table in my database andstore just an id from that name in other table (that id is a foreign key). I will show you my code
//acao model
public function estado() {
return $this->belongsTo('App\Estado');
}
//estado model
public function acao()
{
return $this->hasMany('App\Acao');
}
AcaoController#Create:
public function create()
{
$estado = Estado::pluck('nome', 'id');
return view('Backoffice.acoes.criar_acao', compact('estado'));
}
AcaoController#Store:
$data = Acao::create([
'estado_id' => $data[estado_id],
]);
return redirect()->back();
This way the store doesn´t work and i think that this code doesn´t work with the relationship beetween acao and estado.
Can anyone help me please Thanks

your problem is with Mass Assignment so do this in acao thats has estado_id just add it to your fillable array. add this line tour your model
protected $fillable = ['name','estado_id'];

Related

Laravel Eloquent getting data from relations

I have Task model. My Task model has some relationships and it currently looks like this:
class Task extends Model
{
use HasFactory;
public $timestamps = false;
public function city()
{
return $this->hasOne(City::class, 'id', 'city_id');
}
public function type()
{
return $this->hasOne(Type::class, 'id', 'type_id');
}
public function note()
{
return $this->hasOne(Note::class, 'id', 'note_id');
}
public function operator()
{
return $this->hasOne(User::class, 'id', 'operator_id');
}
}
Now, in my TasksController I need to get Tasks that match certain criteria, like this:
$tasks = Task::whereCityId($city->id)->whereTypeId($type->id)->get()->toArray();
The problem is that fields named city_id type_id note_id operator_id will get my integer values that they have.
Instead I would like to get certain value from a related Model.
For example:
operator_id should be replaced with username from User table that corresponds to the user id.
An obvious solution to this would be to simply use foreach loop, go through my results and get the data I need and simply create another array with the information replaced, but I am not sure if this is the best idea and perhaps there is something better.
You have to change in your code:
$this->hasOne(ClassName::class, 'id', 'foreign_key');
To
$this->belongsTo(ClassName::class, 'foreign_key', 'id');
because Task's id does not available as foreign key in these tables. These table's id present in task table as foreign key so you have to use belongsTo() relationship to tell script from where these id belongs.
Then access properties like this:
$tasks = Task::with("type", "city", "operator")
->whereCityId($city->id)->whereTypeId($type->id)->get();
foreach($tasks as $task){
echo $task->city->name;
}
first you should fix your relation:
public function city()
{
return $this->hasOne(City::class,'city_id','id');
}
and so one the same error, foreign key in argument order comes before the primary key.
after that you can use addSelect:
$tasks = Task::whereCityId($city->id)->whereTypeId($type->id)
->addSelect(['userName' => User::select('name')
->whereColumn('users.id', 'tasks.operator_id')
->limit(1)])->get()->toArray();
i think this will help better than what you ask.
$tasks = Task::whereCityId($city->id)
->whereTypeId($type->id)
->with('operator')
->get()->toArray();
with('operator') is ORM feature that make you collection to include its relation as collection property. In this case it will convert to array property.
you could access it from your foreach function as
#foreach($task as $key)
$key['operator']['username']
#endforeach
Have a nice day

How to get select field in model using laravel?

I want to fetch only the specific column seller_db from seller table with the help of model, but when i used this below code my relationship shows null value, please help me to find my mistake, and how can i fetch selected one field with model using laravel?
here is my User.php file.
User.php
public function sellerDB()
{
$instance = $this->hasOne('\App\Seller', 'user_id', 'id')->select('seller_db');
return $instance;
}
Edit: I made a mistake, I misunderstood your database design, it's necessary add an aditional method to resolve this:
public function seller()
{
return $this->hasOne('\App\Seller', 'user_id', 'id')
}
public function sellerDB()
{
return $this->seller->seller_db;
}
In this case you can call $user->sellerDB() and receive the column seller_db

Failure to extract data from a relationship with laravel

I am trying to make a one-to-many relationship, but I get the following error
Undefined property: stdClass::$client (View:
C:\wamp\www\intranet\resources\views\users\list.blade.php)
The problem is that I am working with an existing database that in the tables does not have id fields, and the foreign keys would also be the typical ones like client_id
My model Client.php
class Client extends Model
{
protected $connection = 'dpnmwin';
protected $table = 'nmundfunc';
public function employee(){
return $this->hasMany('App\Employee');
}
}
My model Employee.php
class Employee extends Model
{
protected $connection = 'dpnmwin';
protected $table = 'nmtrabajador';
public function client(){
return $this->belongsTo('App\Client', 'COD_UND');
}
}
In nmtrabajador COD_UND field would be the foreign key that relates to nmundfunc.
And I try to get the data out like this: {{$user->client->CEN_DESCRI}}.
but it does not throw me the error, how can I solve it?
My Controller where I send in sight
public function index(){
$users = DB::connection('dpnmwin')->table('nmtrabajador')->where('CONDICION', '=', 'A')->get();
return view('users.list',array(
'users' => $users
));
}
You have to call basis on relations.
This code will return you data.
If you have id then you can find by id like below
$employee=Employee::find(1);
Or if you want to fetch all data then you can call all method.
Employee::all();
And then you can just get it by relation as you define in models.
$client=$employee->client->CEN_DESCRI;
Retrieving data from the instance is based on the methods which we have use.
Here in this answer, you can get that
Property [title] does not exist on this collection instance
I hope it will work.
If table doesn't have 'id' as primary key you should specify what the primary key is inside your model:
protected $primaryKey = 'your_primary_key';
Relation looks good, after that you must make sure $user is a defined instance of Employee, because your error probably means that your instance wasn't even defined, so for example if you are using list.blade.php, you need to change the return of your controller and indicate that you want to pass data to your view, for example you could do it like this:
return view('users.list', compact('user'));
Where user is an instance of Employee saved on '$user'
Update
First you should check your user is retrieved properly, you can check it by placing a dd($user)
And when you return a view you can pass information to it, a cleaner way of doing what you are trying to do is what I wrote earlier so you would end up having something like this:
public function index()
{
$users = DB::table('nmtrabajador')
->where('CONDICION', '=', 'A')
->get();
// dd($user) for debugging you are retrieving the user properly
return view('users.list', compact($users));
}

Join with relation between two models not working using non integer primary keys

I have two models: Holiday and HolidayInfo. These look like as follow:
Holiday:
class Holiday extends Model
{
protected $table = 'holidays';
protected $primaryKey = 'holiday_id';
public $timestamps = false;
public function dates(){
return $this->hasOne('App\HolidayDates', 'holiday_id');
}
public function images(){
return $this->hasMany('App\HolidayImages', 'holiday_id');
}
public function info(){
return $this->hasOne('App\HolidayInfo', 'holiday_id');
}
public function pricing(){
return $this->hasOne('App\HolidayPricing', 'holiday_id');
}
}
HolidayInfo:
class HolidayInfo extends Model
{
protected $table = 'holiday_info';
public $timestamps = false;
protected $primaryKey = 'holiday_id';
public function holiday(){
return $this->hasOne('App\Holiday', 'holiday_id');
}
}
My tables:
How can I make use of these models in relation to each-other in my controller while also using a simple where clause? In other words, HolidayInfo has some information which I need as-well as Holiday but it would be more efficient to perform a join somehow and then perform a where statement to narrow the data.
This is what i've tried but it didn't return the correct data:
$holidays = Holidays::with('info')->get();
This is what was returned - as you can see 'info' was returned null.
I have also tried adding a conditional as suggested by iCoders:
Holidays::where('country', $country)->with('info')->get();
Which returns the following suggesting that a join hasnt been performed:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'country' in 'where clause' (SQL: select * from holidays where country = australia)
Country is part of the 'holiday_info' table.
However; performing this query returns the data I need from Holiday Info Table, but it leaves out the Holiday Table data.
$holiday_info = Holidays::find(0)->info()->where('country', $country)->get();
After running the following, over 60 results appear, so the SQL works fine just not the laravel:
SELECT * from holidays JOIN holiday_info ON holidays.holiday_id = holiday_info.holiday_id
How can I combine both models/relations and their data so I can use it in one place?
Yuo have already added relation in Holiday model
public function info(){
return $this->hasOne('App\HolidayInfo', 'holiday_id');
}
You can do something like this using with
Holiday::where(your condition)->with('info')->get();
Updated
public function info(){
return $this->hasOne('App\HolidayInfo', 'holiday_id','holiday_id');
}
if you are not using laravel convention for table fields then you to pass primary key and foreign key to relation
Has One Relation
hasOne($related, $foreignKey, $localKey )
Thanks to #iCoders for helping me crack this case.
The issue was public $incrementing = false; should have been set in the Holiday modal because its a non-integer primary key.
Just use eloquent
$holidays = Holiday::where(your condition)->with("info")->get();
Then when getting the value on your info, just use:
foreach($holidays as $holiday){
$holiday->info->youInfoFieldHere
}

Laravel belongsTo returning null when using 'with'

I'm just getting started with Laravel so please forgive any noobness.
I have a User and Order model, a user has many orders:
# Inside User model
public function orders()
{
$this->hasMany('Order');
}
# Inside Order
public function user()
{
return $this->belongsTo('User');
}
// Not sure if this is upsetting anything (also in Order)
public function products()
{
return $this->belongsToMany('Product');
}
So I think I have the above right.
But when I do this:
$users = User::with('orders')->find(1);
return $users;
I get Call to a member function addEagerConstraints() on null.
However, if I do it the other way around, it works great:
$orders = Order::with('User')->get();
return $orders;
What am I doing wrong / what don't I understand?! Or is my problem bigger than I think?
Database:
The problem is you don't have return for your orders relationship. It should be:
public function orders(){
return $this->hasMany('Order');
}
You should also use your relationships case sensitive. you showed:
$orders = Order::with('User')->get();
is working, but you should rather use
$orders = Order::with('user')->get();
to avoid extra queries to your database in future
For anyone else that runs across this, I was having the same issue, but my problem was that I had the foreign/local keys swapped. Example:
// This is correct for hasX relationships
public function user() {
return $this->hasOne('App\Models\User', 'user_id', 'local_key_user_id');
}
// This is correct for belongsTo relationships
public function user() {
return $this->belongsTo('App\Models\User', 'local_key_user_id', 'user_id');
}
Notice that for hasX relationships, the foreign key is the second parameter, and the local key is the third. However, for belongsTo relationships, these two are swapped.
Probably doesn't answer this particular question but it relates to the title. I had the same issue here is the wrong query
$offer = Offer::with([
'images:name,id,offer_id',
'offer_options:offer_option,value,id,offer_id',
'user:id,name,avatar'])
->select(['id', 'views', 'type', 'status'])
->where('id', $id)->get();
the model look like this
class Offer extends Model {
function user(): BelongsTo {
return $this->belongsTo(User::class);
}
}
The User
class User extends ..... {
function offer(): HasMany {
return $this->hasMany(Offer::class);
}
}
The issue with the query is I was not selecting user_id, i.e in my select function user_id column was not included and that is why I was getting null for user
according to Laravel docs
When using this feature, you should always include the id column and
any relevant foreign key columns in the list of columns you wish to
retrieve.
So the correct query is
$offer = Offer::with([
'images:name,id,offer_id',
'offer_options:offer_option,value,id,offer_id',
'user:id,name,avatar'])
->select(['id', 'views', 'type', 'status','user_id'])
->where('id', $id)->get();

Categories