I have been trying to save the data coming from the dynamically generated fields in the form of an array. I have a oneToMany relationship for the customer table.
I have tried to loop through each field but I am unable to achieve it, please correct me if I am wrong.
public function store(Request $request)
{
$res = $request->all();
$res['address'] = implode(' ', array_values($request->address));
$customer = Customer::create($res);
if ($res) {
$customerData = [];
foreach ($request->department_name as $key => $n) {
$customerData = array(
'department_name' => $request->department_name[$key],
'person_name' => $request->person_name[$key],
'person_number' => $request->person_number[$key],
'person_email' => $request->person_email[$key],
'notification_flag' => !isset($request->notification_flag[$key]) ? 0 : $request->notification_flag[$key] === "on" ? 1 : 0,
'custinvoice_noti' => !isset($request->outstanding[$key]) ? 0 : $request->outstanding[$key] === "on" ? 1 : 0,
'invoice_noti' => !isset($request->invoice[$key]) ? 0 : $request->invoice[$key] === "on" ? 1 : 0,
);
$deptModel[] = new Department($customerData);
$customer->department()->saveMany($deptModel);
}
}
return redirect('admin/customers');
}
Customer model and Department model have the following relationship.
class Customer extends Model
{
protected $fillable = ['owner_name', 'address', 'country', 'state', 'city', 'pincode', 'number', 'correspondance_check'];
public function department()
{
return $this->hasMany('App\Department');
}
}
Department Model.
class Department extends Model
{
protected $fillable = ['customer_id', 'department_name', 'person_name', 'person_number', 'person_email', 'notification_flag', 'notification_type'];
public function customer()
{
return $this->belongsTo('App\Customer');
}
}
public function store(Request $request)
{
$customer = new Customer();
$customer->owner_name = $request['owner_name'];
$customer->country = $request['country'];
$customer->state = $request['state'];
$customer->city = $request['city'];
$customer->pincode = $request['pincode'];
$customer->number = $request['number'];
$customer->correspondance_check = $request['correspondance_check'];
$res = $customer->save();
$cus = Customer::where(['id'=> $res->id])->firstOrFail();
$dep = new Department();
$dep->customer()->associate($cus);
$dep->save();
return redirect('admin/customers');
// return response()->json($customerData);
}
Customer model and Department model have the following relationship.
class Customer extends Model
{
protected $fillable = ['owner_name', 'address', 'country', 'state', 'city', 'pincode', 'number', 'correspondance_check'];
public function department()
{
return $this->hasMany('App\Department');
}
}
//Department Model.
class Department extends Model
{
protected $fillable = ['customer_id', 'department_name', 'person_name', 'person_number', 'person_email', 'notification_flag', 'notification_type'];
public function customer()
{
return $this->belongsTo('App\Customer');
}
}
Related
I have a problem with mapping objects in a Laravel eloquent query.
How to map relations in a query builder.
How to connect two separate collections.
For example. Having models:
class CartProduct extends Model
{
protected $fillable = [
'quantity',
'cart_id',
'product_id',
'unit_price',
'product_code'
];
function product(){
return $this->belongsTo(Product::class);
}
function cart(){
return $this->belongsTo(Cart::class);
}
}
class Cart extends Model
{
function productsInCart()
{
return $this->hasMany(CartProduct::class);
}
public function products()
{
return $this->belongsToMany(
Product::class,
'cart_products',
'cart_id',
"product_id");
}
}
class Product extends Model
{
protected $fillable = [
'name',
'code',
'description',
'price',
];
}
The tasks are:
Get a set of products that are in the same cart (doesn't matter which one) as $product_id (excluding $product_id)
Get a set of products that were in any cart together with $product_id (excluding $product_id, without duplications)
I would solve it like this:
1.
public function task_one($product_id)
{
return $products = CartProduct::where('product_id', $product_id)->first()->cart->products
->filter(function (Product $p) use ($product_id) {
return $p->id !== $product_id;
});
}
public function task_two($product_id)
{
$cartProducts = CartProduct::where('product_id', $product_id)->get();
$products = collect(new Product);
foreach ($cartProducts as $cartProduct) {
$productsInCart = $cartProduct->cart->products
->filter(function (Product $p) use ($product_id) {
return $p->id !== $product_id;
});
$products = $products->merge($productsInCart);
}
return $products->unique();
}
However, the 2nd function seems to be awful. How can I do this properly, to achieve fast execution and a good style of code?
Is there any method to "map" the whole collection to related model objects? For example by
$carts = CartProduct::getByProductId($product_id)->"mapByRelationship('cart)";
//The result should be a collection od Carts
$products = CartProduct::getByProductId($product_id)->"mapByRelationship('cart)"->"mapByRelationship('products')"->unique();
//The result should be the same as task_two($product_id);
Thank you in advance
I think I have done this Controller-Model Relationship.
Controller:
class MakeAWishController extends Controller
{
public function getMakeAWishes(Request $request)
{
$limit = (int) ($request->limit ?? 1);
$offset = (int) ($limit * (($request->page ?? 1) - 1));
$wishes = MakeAWish::with('product')
->offset($offset)->limit($limit)->where('product_quantity', '>' , '0')->get()
->map(function ($wish) {
$wish->children_image = asset(Storage::url($wish->children_image));
if(!empty($variant = $wish->product->variant())) {
$wish->product->variant_id = $variant->variant_id;
$wish->product->variant_price = $variant->variant_price ?? "0.00";
$wish->product->variant_compare_at_price = $variant->variant_compare_at_price ?? "0.00";
}
return $wish;
});
$response = [
'status' => 200,
'data' => $wishes
];
return response()->json($response);
}
}
Model:
class MakeAWish extends Model
{
protected $collection = 'make_a_wishes';
protected $fillable = [
'children_name',
'children_name_for_isis',
'age',
'country',
'children_image',
'product_id',
'quantity'
];
protected $casts = [
'product_id' => 'string'
];
public function product()
{
return $this->hasOne(Product::class, 'product_id', 'product_id');
}
public function orders()
{
return $this->hasMany(OrderHistory::class, 'type_id', '_id');
}
public function orderCount()
{
return $this->orders()->where('type', 'M')->count();
}
}
I have four tables:
Agroindustria
Pessoa
PessoaJuridica
Endereco
. Here are their Models:
Agroindustria
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Agroindustria extends Model
{
use SoftDeletes;
protected $table = "agroindustria";
protected $primaryKey = "CodAgroindustria";
public $incrementing = false;
protected $keyType = 'string';
public $fillable = ['CodAgroindustria, Porte'];
public $hidden = ['created_at', 'updated_at', 'deleted_at'];
public function pessoa () {
return $this->setConnection('diana')->hasOne(Pessoa::class, 'CodPessoa', 'CodAgroindustria');
}
public function pessoajuridica()
{
return $this->setConnection('diana')->hasOne(PessoaJuridica::class, 'CodPessoa', 'CodEndereco');
}
public function endereco()
{
return $this->setConnection('diana')->hasOne(PessoaJuridica::class, 'CodEndereco', 'CodEndereco');
}
public function estado(){
return $this->setConnection('diana')->hasOne(Estado::class, 'CodEstado', 'estado');
}
public function cidade(){
return $this->setConnection('diana')->hasOne(Cidade::class, 'CodCidade', 'cidade');
}
}
Pessoa:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Pessoa extends Model
{
// use SoftDeletes;
protected $table = "pessoa";
protected $primaryKey = "CodPessoa";
public $incrementing = false;
protected $keyType = 'string';
protected $connection = "diana";
public $hidden = ['created_at', 'updated_at', 'EXCLUIDO', 'LastSend'];
public $fillable = ['email', 'TelRes', 'TelCel'];
public function endereco()
{
return $this->hasOne('App\Endereco', 'CodEndereco', 'CodEndereco');
}
public function pessoafisica()
{
return $this->hasOne('App\PessoaFisica', 'CodPessoaFisica', 'CodPessoa');
}
public function pessoajuridica()
{
return $this->hasOne('App\PessoaJuridica', 'CodPessoaJuridica', 'CodPessoa');
}
}
The PessoaJuridica and Endereco Models are pretty much the same as the Pessoa Model.
When I soft delete my Agroindustria, the deleted_at column updates successfully, but I'm struggling with updating the EXCLUIDO column values from 0 to 1 in my other models.
Here's the delete function I created in my AgroindustriaController:
public function deletar (Request $request)
{
try {
$Agroindustria = Agroindustria::where('CodAgroindustria', $request['CodAgroindustria']);
$Agroindustria->delete();
$Pessoa = Pessoa::findOrFail($request['CodPessoa']);
if ($Agroindustria->delete()) {
DB::table('Pessoa')->where('CodPessoa', $Pessoa->CodPessoa)
->update(array('EXCLUIDO' => 1));
}
return response()->json([
'error' => false,
'data' => [
'message' => 'Dados deletados com sucesso',
]
]);
} catch (Exception $e) {
return response()->json([
'error' => true,
'message' => [$e->getMessage()]
]);
}
}
second line in try
$Agroindustria->delete();
write this line like this
$dlt = $Agroindustria->delete();
after that in your if condition put this variable $dlt like this
if ($dlt) {
DB::table('Pessoa')->where('CodPessoa', $Pessoa->CodPessoa)
->update(array('EXCLUIDO' => 1));
}
Solved it by doing:
$Agroindustria = Agroindustria::where('CodAgroindustria', $request['CodAgroindustria']);
$dlt = $Agroindustria->delete();
if ($dlt) {
Pessoa::where('CodPessoa', $request['CodPessoa'])
->update(array('EXCLUIDO' => 1));
PessoaJuridica::where('CodPessoaJuridica', $request['CodPessoaJuridica'])
->update(array('EXCLUIDO' => 1));
Endereco::where('CodEndereco', $request['CodEndereco'])
->update(array('EXCLUIDO' => 1));
}
Thank you all!
i have relation between Service and Services_Gallery one to many, and i want to use id of Service when i insert new image to Services_Gallery, and this is my Controller:
public function save(Request $request)
{
$this->validate($request,[
'image' => 'required|image|mimes:jpeg,jpg,png,svg|max:1024'
]);
$services_Gallery = new Services_Gallery();
$services_Gallery->image = $request->image->move('Uploads', str_random('6') . time() . $request->image->getClientOriginalName());
$services_Gallery->Service::all(id) = $request->service_id; //The problem here
$services_Gallery->save();
return back();
}
this is my Models:
class Service extends Model
{
protected $table = 'services';
protected $fillable = [
'en_main_title',
'ar_main_title',
'en_sub_title',
'ar_sub_title',
'en_content_title',
'ar_content_title',
'en_content',
'ar_content',
'priority',
];
public function gallery()
{
return $this->hasMany('App\Services_Gallery','service_id');
}
}
class Services_Gallery extends Model
{
protected $table = 'services_galleries';
protected $fillable = [
'image',
'service_id',
];
public function gallery(){
return $this->belongsTo('App\Service','service_id');
}
}
Exapmle:
$modelOfService = Service::where('param_x', $request->service_id)->first();
$id = $modelOfService->id;
Is that you need?
I am trying to save datas into two different tables depends on selection(x-editable). Here is my code and Help me by pointing where i am doing mistake.
Result i am looking for: I change payment status pending to paid in TBL:Product, paid values also change 0 to 1 in TBL:Product_payment
TBL:Product
- product_id
- client_id
...
- status {paid/pending}
TBL:Product_payment
- product_id
- payment_id
....
- paid {1/0}
Controller:
public function update()
{
$inputs = Input::all();
if ($row = Product::with('payments')->find($inputs['pk']))
{
$row->$inputs['name'] = $inputs['value'];
if($row['status'] == 'paid') {
$row['paid'] = 1;
}
$row->save();
return $row;
}
Product.php(model)
class Product extends Eloquent
{
protected $primaryKey = 'product_id';
protected $table = 'products';
protected $fillable = array('client_id', 'date', 'amount', 'status', 'notes');
public function payments()
{
return $this->hasMany('ProductPayment');
}
}
ProductPayment.php(model)
class ProductPayment extends Eloquent
{
public $table = 'product_payments';
protected $primaryKey = 'product_payment_id';
protected $fillable = array('product_id', 'client_id', 'payment_method', 'amount_paid', 'paid');
public function product()
{
return $this->belongsTo('Products');
}
public function clients()
{
return $this->belongsTo('Clients');
}
}
Add a model event listener to boot in your AppServiceProvider for whenever an instance of Product is saved.
Product::saved(function ($product) {
$paymentStatus = [
'pending' => 0,
'paid' => 1,
];
if(array_key_exists($product->status, $paymentStatus))
{
ProductPayment::where('product_id', $product->id)
->update(['paid' => $paymentStatus[$product->status]]);
}
});
I use PHP, Laravel 5.2 and MySQL.
During user registration, I need to create a new Patient. But, Patient has user id, contact id and guardian id(foreign keys).
When I try to save() the patient, I get the following exception:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'patient_id' in
'field list' (SQL: update users set patient_id = 0, updated_at =
2016-06-07 12:59:35 where id = 6)
The problem is that I DO NOT have patient_id column. Instead I have patientId.
I don't know how to fix this issue. Any help will be appreciated. I can include the migration files if this is important.
UserController.php
public function postSignUp(Request $request)
{
$this->validate($request,[
'email' => 'required|email|unique:users',
'name' => 'required|max:100',
'password' => 'required|min:6'
]);
$guardian = new Guardian();
$guardian->guardianId = Uuid::generate();;
$guardian->save();
$contact = new Contact();
$contact->contactId = Uuid::generate();
$contact->save();
$user = new User();
$user->email = $request['email'];
$user->name = $request['name'];
$user->password = bcrypt($request['password']);
$user->save();
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->user()->save($user);
$patient->contact()->save($contact);
$patient->guardian()->save(guardian);
$patient->save();
Auth::login($user);
// return redirect()->route('dashboard');
}
Patient.php
class Patient extends Model
{
protected $primaryKey='patientId';
public $incrementing = 'false';
public $timestamps = true;
public function user()
{
return $this->hasOne('App\User');
}
public function contact()
{
return $this->hasOne('App\Contact');
}
public function guardian()
{
return $this->hasOne('App\Guardian');
}
public function allergies()
{
return $this->belongsToMany('App\PatientToAllergyAlert');
}
public function medicalAlerts()
{
return $this->belongsToMany('App\PatientToMedicalAlert');
}
}
User.php
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function patient()
{
return $this->belongsTo('App\Patient');
}
}
Contact.php
class Contact extends Model
{
protected $table = 'contacts';
protected $primaryKey = 'contactId';
public $timestamps = true;
public $incrementing = 'false';
public function contact()
{
return $this->belongsTo('App\Patient');
}
}
Guardian.php
class Guardian extends Model
{
protected $table = 'guardians';
protected $primaryKey = 'guardianId';
public $timestamps = true;
public $incrementing = 'false';
public function contact()
{
return $this->belongsTo('App\Patient');
}
}
You have not defined relationships correctly. First of all, fill in table fields into $fillable array in Patient, Contact, Guardian classes (just like in User class).
If you want to use hasOne relationship between Patient and User, you're gonna need user_id field on patients table. You can alternatively use belongsTo relationship.
If you want to use custom column names, just specify them in relationship methods:
public function user()
{
return $this->hasOne('App\User', 'id', 'user_id');
// alternatively
return $this->belongsTo('App\User', 'user_id', 'id');
}
Just go through documentation without skipping paragraphs and you will get going in a few minutes :)
https://laravel.com/docs/5.1/eloquent-relationships#defining-relationships
Also, this will not work:
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->user()->save($user);
new Patient() only creates the object, but does not store it in DB, so you will not be able to save relationships. You need to create the object and store it to DB to avoid this problem:
$patient = Patient::create(['patientId' => (string)Uuid::generate()]);
$patient->user()->save($user);
...
// or
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->save();
$patient->user()->save($user);
...
When you're setting up your relationship, you can to specify the name of the primary key in the other model. Look here.
I'm not sure, but I think you relationships are not defined properly.