Can't get variable from Laravel ORM relations - php

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 ]);

Related

How to validate nested relation in request class in laravel

I have two model that are related.
Models
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Address extends Model
{
use HasFactory;
protected $fillable = [
'city',
'post_code',
'street',
'country'
];
protected $hidden = [
'created_at',
'updated_at',
'addressable_id',
'addressable_type'
];
public function addressable(): MorphTo
{
return $this->morphTo();
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Club extends Model
{
use HasFactory;
protected $fillable = [
'name',
'email',
'phone',
'description',
'user_id'
];
protected $hidden = [
'created_at',
'updated_at'
];
public function address()
{
return $this->morphMany(Address::class, 'addressable');
}
}
For that models i've got Request class with validator rules.
Requests
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreAddressRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'city' => 'required|string|max:125',
'post_code' => 'required|string',
'street' => 'required|string',
'country' => 'required|string| max:125'
];
}
}
<?php
namespace App\Http\Requests;
use App\Traits\FailedValidation;
use Illuminate\Foundation\Http\FormRequest;
class StoreClubRequest extends FormRequest
{
use FailedValidation;
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|string|max:125',
'description' => 'required|string',
'email' => 'email:dns',
'phone' => 'string|max:125',
// 'address' => (new StoreAddressRequest)->rules(), ???
'images' => 'required|image'
];
}
}
Trying to create new club with address.
I'm sending request to API like that:
[
"name":"dfsdf",
"dsfsdf":"sdfsdf",
"address": {
"city": "name",
"post_code":"46-454"
}
]
Address may be added standalone or from other model that are related too.
Now only fields from club request are validated.
How to validate club and address request?

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

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);

Eloquent relationships in laravel Problems

I'm having issues with how to deal with tables relationships in laravel. i have three tables Orders table, Order_product table and User table. A User can either be described as a seller or a buyer depending on if they listed or bought something. Now when a user submit order form i get an error
"General error: 1364 Field 'seller_id' doesn't have a default value (SQL: insert into order_product (order_id, product_id, quantity, `up ▶"
Here is how those tables look like in phpmyAdmin
https://imgur.com/a/fvxo1YZ
And below are the models
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'Seller'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
//public function isSeller() {
// return $this->seller;
//}
public function products()
{
return $this->hasMany(Products_model::class);
}
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function orders()
{
return $this->hasManyThrough(Order::class, Products_model::class, 'buyer_id', 'seller_id', 'product_id');
}
public function orderFromBuyers()
{
return $this->hasManyThrough(OrderProduct::class, Products_model::class, 'buyer_id', 'product_id');
}
public function orderFromSellers()
{
return $this->hasManyThrough(OrderProduct::class, Products_model::class, 'seller_id', 'product_id');
}
}
Products_model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class products_model extends Model
{
protected $table='products';
protected $primaryKey='id';
protected $fillable= ['seller_id','pro_name','pro_price','pro_info','image','stock','category_id'];
}
OrderProduct.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class OrderProduct extends Model
{
protected $table = 'order_product';
protected $fillable = ['order_id', 'buyer_id', 'seller_id','product_id', 'quantity'];
public function products()
{
return $this->belongsTo('App\Products_model');
}
public function buyer()
{
return $this->belongsTo(User::class, 'id', 'buyer_id');
}
public function seller()
{
return $this->belongsTo(User::class, 'id', 'seller_id');
}
public function order()
{
return $this->belongsTo(Order::class);
}
}
Order.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
//protected $table = 'orders';
protected $fillable = [
'shipping_email', 'shipping_name', 'shipping_city', 'shipping_phone', 'billing_subtotal', 'billing_total',
];
public function user()
{
return $this->belongsTo('App\User');
}
public function products()
{
return $this->belongsToMany('App\Products_model')->withPivot('quantity');
}
public function orders(){
return $this->hasMany('App\OrderProduct', 'order_id');
}
}
Here is my store Function
public function store(Request $request)
{
//Insert into orders table
$order = Order::create([
'buyer_id' => auth()->user() ? auth()->user()->id : null,
'shipping_email' => $request->email,
'shipping_name' => $request->name,
'shipping_city' => $request->city,
'shipping_phone' => $request->phone,
// 'error' => null,
]);
//Insert into order product table
if ($order) {
foreach(session('cart') as $productId =>$item) {
if (empty($item)) {
continue;
}
OrderProduct::create([
'order_id' => $order->id ?? null,
'product_id' => $productId,
// $products=DB::table('products')->where('id',$id)->get();
'quantity' => $item['quantity'],
//dd($item)
]);
}
}
//Empty Cart After order created
$cart = session()->remove('cart');
return redirect()->route('confirmation.index')->with('success_message', 'Thank you! Your payment has been successfully accepted!');
}
the error is very specific:
General error: 1364 Field 'seller_id' doesn't have a default value
(SQL: insert into order_product
And looking at the code you posted, assume it happens here:
OrderProduct::create([
'order_id' => $order->id ?? null,
'product_id' => $productId,
'quantity' => $item['quantity'],
]);
You can not create an OrderProduct without giving a value to seller_id when that field doesn't have a default value or is not nullable in DB. So, give it a value when creating the record. Looking at the models, I think you could do something like this:
$product = products_model::find($productId);
OrderProduct::create([
'order_id' => $order->id ?? null,
'product_id' => $productId,
'quantity' => $item['quantity'],
'seller_id' => $product->seller_id,
'buyer_id' => $order->buyer_id,
]);
You need to send value of the seller id.
$order = Order::create([
'buyer_id' => auth()->user() ? auth()->user()->id : null,
'seller_id' => $request->seller_id,
'shipping_email' => $request->email,
'shipping_name' => $request->name,
'shipping_city' => $request->city,
'shipping_phone' => $request->phone,
// 'error' => null,
]);
or you can remove the seller_id on your Order Table because you can get the seller information from the Product Model
Post model to relationship one to one,
and User model to relationship one to many.

Laravel - Model BelongsTo multiple models

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');
}
}

Categories