Laravel - Model BelongsTo multiple models - php

I am developing a system and I have a question, in the system I have 3 main models (User, State, City), to manage the users I use a package for Laravel called Entrust, with this package I can define system roles, one of these roles is the manager, the manager can have Cities and States, however, a States can have several Cities, so in my model Cities BelongsTo to a User and a States.
Is that correct? A model can BelongsTo more then one model? I found no satisfactory answer on Google.
User.php
class User extends Authenticatable
{
use Notifiable;
use EntrustUserTrait;
use SearchableTrait;
protected $fillable = [
'role',
'active',
'status',
'name',
'slug',
'email',
'password',
'cpf',
'rg',
'mothers_name',
'marital_status',
'curriculum',
'psychiatric_report',
'contract',
'phone',
'adress',
'city',
'state',
'country',
];
protected $hidden = [
'password', 'remember_token',
];
protected $searchable = [
'columns' => [
'users.name' => 10,
'users.slug' => 8,
'users.email' => 8,
]
];
public function getRouteKeyName()
{
return 'slug';
}
public function states()
{
return $this->hasMany('App\State');
}
public function cities()
{
return $this->hasMany('App\City');
}
}
State.php
class State extends Model
{
protected $fillable = [
'name',
'slug',
'initials',
'manager_id'
];
public function getRouteKeyName()
{
return 'slug';
}
public function manager(){
return $this->belongsTo('App\User');
}
public function cities(){
return $this->hasMany('App\City');
}
}
City.php
class City extends Model
{
protected $fillable = [
'name',
'slug',
'state_id',
'manager_id',
];
public function getRouteKeyName()
{
return 'slug';
}
public function manager(){
return $this->belongsTo('App\User');
}
public function state(){
return $this->belongsTo('App\State');
}
}

Related

How to get relation with a alias Model

Hello i have a model named Product and 2 model named ProductImage and ProductAttribute
What i wish ?
I want to access to the product attribute and get they element with this:
Product:with(['attribute','image','category']);
If i will access to the attribute laravel return me this error
Syntax error or access violation: 1066 Not unique table/alias: 'product_attributes'
in my Product Model
class Product extends Model
{
protected $fillable = [
'name',
'description',
'category_id',
];
protected $guarded = [
'id',
];
protected $dates = [
'created_at',
'updated_at',
];
public function category()
{
return $this->belongsTo(Category::class);
}
public function attribute()
{
return $this->belongsToMany(ProductAttributes::class,'product_attributes');
}
}
In my ProductAttribute Model
class ProductAttributes extends Model
{
protected $fillable = [
'attribute',
'value',
'price',
'product_id',
'stock'
];
public function product()
{
return $this->belongsTo(Product::class);
}
}
Comment: I'm using laravel as REST API

Can't get variable from Laravel ORM relations

I want to get "$invoice->form->form" parameter here because i want to use it in view. When i am using dd($invoice->form); than gets null. Invoice and form are other tables and models but are connected with laravel relationship and foreign keys in migrations.
public function show(Invoice $invoice)
{
dd($invoice->form);
return view('invoices.show',compact('invoice'));
}
This is begining of invoice controller file:
namespace App\Http\Controllers;
use Kyslik\ColumnSortable\Sortable;
use App\Invoice;
use Illuminate\Http\Request;
use App\User;
use App\Proform;
use App\Form;
use App\Currency;
use DB;
Here is invoice model
<?php
namespace App;
use Kyslik\ColumnSortable\Sortable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Invoice extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
use SoftDeletes;
use Sortable;
protected $table = 'invoices';
protected $fillable = [
'invoicenumber', 'invoicedate', 'id', 'selldate', 'user_id', 'paymentmethod',
'paymentdate', 'status', 'comments', 'city', 'paid', 'autonumber', 'automonth', 'autoyear', 'name',
'PKWIU', 'quantity', 'unit', 'netunit', 'nettotal',
'VATrate', 'grossunit', 'grosstotal', 'form_id', 'currency_id',
];
public $sortable = [ 'invoicenumber', 'invoicedate', 'id', 'selldate', 'user_id', 'paymentmethod',
'paymentdate', 'status', 'comments', 'city', 'paid', 'autonumber', 'automonth', 'autoyear', 'name',
'PKWIU', 'quantity', 'unit', 'netunit', 'nettotal',
'VATrate', 'grossunit', 'grosstotal', 'form_id', 'currency_id',
];
protected $dates = ['deleted_at'];
public $primaryKey = 'id';
public function user()
{
return $this->belongsTo('App\User');
}
public function form()
{
return $this->hasOne('App\Form');
}
public function currency()
{
return $this->hasOne('App\Currency');
}
public function proform()
{
return $this->belongsTo('App\Proform');
}
}
Here is form model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Form extends Model
{
//
protected $fillable = [
'id', 'form',
];
public function invoice()
{
return $this->belongsTo('App\Invoice');
}
public function proform()
{
return $this->belongsTo('App\Proform');
}
}
Because you aren't loading the relation.
On your controller you should query like: $invoice = Invoice::with('form')->find($invoice_id); and return it to the view like: return view('invoices.show', [ 'invoice' => $invoice->form ]);

Update object in relations in Laravel

I am beginner in Laravel. I use in my project Laravel 5.8.
I have this code :
class Client extends Authenticatable
{
use SoftDeletes, Deactivation, Notifiable;
protected $fillable = [
'email',
'email_verified_at',
'password_assigned_at',
'verify_token',
'password',
'type'
];
protected $hidden = [
'password',
'verify_token',
'remember_token',
];
protected $dates = [
'password_assigned_at',
'email_verified_at',
'created_at',
'updated_at',
'deactivated_at',
'deleted_at',
];
public function invoiceAddress()
{
return $this->hasOne('App\Models\Addresses', 'client_id', 'id');
}
}
and Adress:
class Addresses extends Model
{
use SoftDeletes;
protected $fillable = [
'user_id',
'company_name',
'nip',
'address',
'city',
'postal_code'
];
protected $dates = [
'deleted_at'
];
public function client()
{
return $this->belongsTo(Client::class);
}
}
In controller I have:
$bla = Client::with('invoiceAddress')->where('id', 1)->get();
I want update object in relation invoiceAddress.
I make code to normal update. I try this code:
$data = [
'client_id' => $id,
'company_name' => $request->input('company_invoice_company_name'),
'nip' => $request->input('company_invoice_nip'),
'address' => $request->input('company_invoice_address'),
'city' => $request->input('company_invoice_city]'),
'postal_code' => $request->input('company_invoice_postal_code'),
];
$client->invoiceAddress()->update($data);
but this is not working. How can I make it?
I need update object in relation. My code not working
In your $fillable of Addresses is saying user_id and in relationship you've used client_id
change client_id to user_id
public function invoiceAddress()
{
return $this->hasOne('App\Models\Addresses', 'user_id', 'id');
}
One more issue I can see is you're using get() method it should be first();
$bla = Client::with('invoiceAddress')->where('id', 1)->first();
$bla->invoiceAddress()->update($data);

Inserting values to a form with relationship in laravel (Referring projectid)

There is a a single form which takes in details and save it to 4 different tables in db. Project, Events, Donation and Opportunities. Project has many Events, many Donation and many Opportunities. I want to use the project id in other tables as well. but when I save the Form the details are stored in each 4 tables but the project is not been taken for the other 3 tables Events, Donation and Opportunity. Its value is 0. How to take that particular project id(auto-increment) in all other three tables.
My ProjectController is like this:
class ProjectController extends Controller
{
public function getProject()
{
return view ('other.project');
}
public function postProject(Request $request)
{
$this->validate($request, [
'ptitle' => 'required|max:200',
'pdescription' => 'required',
'etitle' => 'required|max:200',
'edetails' => 'required',
'dtotal' => 'required',
'oposition' => 'required|max:100',
'odescription' => 'required',
]);
Project::create([
'ptitle' => $request->input('ptitle'),
'pdescription' => $request->input('pdescription'),
'pduration' => $request->input('pduration'),
'psdate' => $request->input('psdate'),
'pedate' => $request->input('pedate'),
'pcategory' => $request->input('pcategory'),
'pimage' => $request->input('pimage'),
]);
Event::create([
'pro_id' => $request->input('pid'),
'etitle' => $request->input('etitle'),
'pdetails' => $request->input('pdetails'),
'edate' => $request->input('edate'),
'etime' => $request->input('etime'),
'elocation' => $request->input('elocation'),
'eimage' => $request->input('eimage'),
]);
Donation::create([
'pro_id' => $request->input('pid'),
'dtotal' => $request->input('dtotal'),
'dinhand' => $request->input('dinhand'),
'dbankaccount' => $request->input('dbankaccount'),
]);
Opportunity::create([
'pro_id' => $request->input('pid'),
'oposition' => $request->input('oposition'),
'odescription' => $request->input('odescription'),
'olocation' => $request->input('olocation'),
'odeadline' => $request->input('odeadline'),
]);
return redirect()
->route('home')
->with('info', 'Your project has been created.');
}
My Project Model:
class Project extends Model
{
use Notifiable;
protected $fillable = [
'ptitle',
'pdescription',
'pduration',
'psdate',
'pedate',
'pcategory',
'pimage',
];
public function events()
{
return $this->hasMany('Ngovol\Models\Event', 'pro_id');
}
public function donations()
{
return $this->hasMany('Ngovol\Models\Donation', 'pro_id');
}
public function opportunities()
{
return $this->hasMany('Ngovol\Models\Event', 'pro_id');
}
protected $hidden = [
];
}
Event Model:
class Event extends Model
{
use Notifiable;
protected $table = 'events';
protected $fillable = [
'pro_id',
'etitle',
'edetails',
'edate',
'etime',
'elocation',
'eimage',
];
public function projects()
{
return $this->belongsTo('Ngovol\Models\Project', 'pro_id');
}
}
Donation Model:
class Donation extends Model
{
use Notifiable;
protected $fillable = [
'pro_id',
'dtotal',
'dinhand',
'drequired',
'dbankaccount',
];
protected $hidden = [
];
public function projects()
{
return $this->belongsTo('Ngovol\Models\Project', 'pro_id');
}
}
Opportunity Model:
class Opportunity extends Model
{
use Notifiable;
protected $fillable = [
'pro_id',
'oposition',
'odescription',
'olocation',
'odeadline',
];
protected $hidden = [
];
public function projects()
{
return $this->belongsTo('Ngovol\Models\Project', 'pro_id');
}
}
Better try following code
$project = Project::create( $request->only(['ptitle', 'pdescription', 'pduration', 'psdate', 'pedate', 'pcategory', 'pimage']));
$project->events()->create( $request->only(['etitle', 'pdetails', 'edate', 'etime', 'elocation', 'eimage']));
$project->donations()->create($request->only(['dtotal', 'dinhand', 'dbankaccount']));
$project->opportunities()->create($request->only(['oposition','odescription','olocation','odeadline']));

Laravel 5.3: Eloquent hasMany update

I need to update the items for specific order with Eloquent.
I have this models:
class Orders extends \Illuminate\Database\Eloquent\Model
{
public $timestamps = false;
protected $fillable = ['items_array'];
public function items()
{
return $this->hasMany(Items::class, 'order_id', 'order_id');
}
public function setItemsArrayAttribute($data)
{
$this->items()->whereIn('article_id', array_map(function($item){
return $item['article_id'];
}, $data['items']))->update($data);
}
}
class Items extends \Illuminate\Database\Eloquent\Model
{
protected $table = 'order_to_items';
public $timestamps = false;
protected $fillable = ['internal_code'];
public function order()
{
return $this->belongsTo(Orders::class, 'order_id', 'order_id');
}
}
I have the api response like that:
$response = [
'message'=>'some',
'order_id'=>'111-222-333',
'items'=>[
[
'article_id' => 'R-320108',
'internal_code' => 333
],
[
'article_id' => 'R-320116',
'internal_code' => 444
],
]
];
So I make this
$order = Orders::where('order_id', $response['order_id'])->with('items')->first();
and I was trying to make this:
$order->update([
'is_sent' => true,
'items_array' => $response['items']
]);
but that doesn't work. Is there any way to match the related model with API response and make update?
Thanks!
You can use save():
$order->is_sent = true;
$order->items_array = $response['items'];
$order->save();
Or update():
$order = Orders::where('order_id', $response['order_id'])
->update([
'is_sent' => true,
'items_array' => $response['items']
]);

Categories