Laravel 5.3: Eloquent hasMany update - php

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

Related

Retrieving eloquent api resource using keyby collection method

I have an end API point
users/{user}
now in User resource, I want to return
public function toArray($request)
{
// return parent::toArray($request);
return [
'id' => $this->id,
'name' => $this->name,
// 'comments' => $this->post->comments->keyBy('post_id')
'comments' => new CommentCollection($this->post->comments->keyBy->post_id)
];
}
CommentCollection class
public function toArray($request)
{
// return parent::toArray($request);
return [
'data' => $this->collection->transform(function($comment){
return [
'id' => $comment->id,
'comment' => $comment->comment,
];
}),
];
}
but the result will not include the post_id as key, how I can make it return the comments collection having key post_id?
Update
use App\models\Post;
use App\Http\Resources\Postas PostResource;
Route::get('/posts', function () {
return PostResource::collection(Post::all()->keyBy->slug);
});
This is working correctly, but if I will use post collection inside User resource as relationship, it is not working! and that is my requirement in comments collection.
What I did it, I created another ResourceGroupCollection class
<?php
namespace App\Http\Resources\Collection;
use Illuminate\Http\Resources\Json\ResourceCollection;
class CommentGroupCollection extends ResourceCollection
{
public $collects = 'App\Http\Resources\Collection\CommentCollection';
public $preserveKeys = true;
public function toArray($request)
{
return $this->collection;
}
}
<?php
namespace App\Http\Resources\Collection;
use Illuminate\Http\Resources\Json\ResourceCollection;
class CommentCollection extends ResourceCollection
{
public $collects = 'App\Http\Resources\Comment';
public $preserveKeys = true;
public function toArray($request)
{
return $this->collection;
}
}
and then
new CommentGroupCollection($comments->groupBy('post_id')),
just like this :
public function toArray($request)
{
// return parent::toArray($request);
return [
'id' => $this->id,
'name' => $this->name,
// 'comments' => $this->post->comments->keyBy('post_id')
'comments' => new CommentCollection($this->post->comments)->keyBy('post_id')
];
}

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.

Return many object in my json response using resource

I'm kinda new to Laravel and I hope someone we'll be able to give me some help.
I apologize for my english
So I'm trying to develop an application with some friends to manage our food by sending alert when the peremption date is near.
I'm developing the API, the actual structure is this way:
A user,
A product,
A basket containing the user_id, the product_id and of course the peremption date.
So now when I make a call to get the User 'stock' on my API I wish I could get something like this:
{
'id' : 1,
'peremption_date': XX-XX-XX,
'product' : {
'id' : 3,
'name': bblablabala,
'brand' : blablabala
},
'id' : 2,
'peremption_date': XX-XX-XX,
'product' : {
'id' : 4,
'name': bblablabala,
'brand' : blablabala
},
}
So I took a look on resources and saw that if I define the right relations, this could do the stuff for my output.
I'll link you my actual class declarations and their resources:
User:
//user.php
class User extends Authenticatable
{
use Notifiable, HasApiTokens;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function baskets()
{
return $this->hasMany(Basket::class);
}
}
Product:
//Product.php
class Product extends Model
{
protected $table = 'products';
protected $fillable = ['code_barre', 'product_name', 'generic_name', 'brand', 'quantity'];
public function basket()
{
return $this->belongsToMany(Basket::class);
}
}
//productResource.php
class ProductResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'code_barre' => $this->code_barre,
'product_name' => $this->product_name,
'generic_name' => $this->generic_name,
'brand' => $this->brand,
'quantity' => $this->quantity,
'created_at' => (string) $this->created_at,
'updated_at' => (string) $this->updated_at,
];
}
}
Basket:
//Basket.php
class Basket extends Model
{
protected $table = 'baskets';
protected $fillable = ['user_id', 'product_id', 'dlc_date'];
public function user()
{
return $this->belongsTo(User::class);
}
public function product()
{
return $this->hasOne(Product::class);
}
}
//BasketResource.php
class BasketResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'dlc_date' => (string) $this->dlc_date,
'created_at' => (string) $this->created_at,
'updated_at' => (string) $this->updated_at,
'product' => $this->product
];
}
}
So when I try to store a new basket in my store method:
//BasketController.php
public function store(Request $request)
{
$this->product->storeProduct($request->input('code_barre'));
$att = DB::table('products')
->where('code_barre', '=', $request->input('code_barre'))
->first();
$basket = Basket::create([
'user_id' => $request->user()->id,
'product_id' => $att->id,
'dlc_date' => $request->input('dlc_date')
]);
return new BasketResource($basket);
}
I get the following error (this one)
saying than products.id_basket does not exist and its right, it's not supposed to exist. This is Basket who have a product_id. so I know this is coming from the relationship I declared but I can't figure how to do it right.
Can someone come and save me ???
Thanks a lot, I hope you understood me !
Wish you a good day
As I look at your Basket model, it seems you have to change your:
public function product()
{
return $this->hasOne(Product::class);
}
to:
public function product()
{
return $this->belongsTo(Product::class);
}
Because you have product_id in your baskets table. To use hasOne() relation, you will need to remove product_id from baskets table and add basket_id to products table, because hasOne() relation is something like hasMany(), only calling ->first() instead of ->get()

Laravel Eloquent : The wrong key name for model's relation

I made a Models controller and use it as resources for almost all my Model. Now, when I try to get the data of a model and the related models, Laravel replace upper case letter with an underscore and the lower case letter. I need to let it with the upper case.
So there is the model where I got the issue at App\Models\Rate:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Rate extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $table = 'rates';
protected $fillable = [
'institution_id',
'name',
];
protected $info = [
'relations' => [
'rateRistournes' => [
'model' => 'RateRistourne',
'type' => 'hasMany',
],
'rateRows' => [
'model' => 'RateRow',
'type' => 'hasMany',
],
'rateTables' => [
'model' => 'RateTable',
'type' => 'hasMany',
],
],
'rules' => [
],
'hashid' => false,
];
public function getRelations()
{
return $this->info['relations'];
}
public function getRules()
{
return $this->info['rules'];
}
public function useHashid()
{
return $this->info['hashid'];
}
public function institution()
{
return $this->belongsTo(Institution::class);
}
public function rateTables()
{
return $this->hasMany(RateTable::class);
}
public function rateRows()
{
return $this->hasMany(RateRow::class);
}
public function rateRistournes()
{
return $this->hasMany(RateRistourne::class);
}
}
And this is the function that contain the query into ModelsController:
public function show($name, $id)
{
$data = $this->retrieveModelAndRelations($name, $id);
if (is_null($data)) {
return $this->sendError('Model not found.');
}
return $this->sendResponse($data->toArray(), 'Model retrieved successfully.');
}
private function retrieveModelAndRelations($name, $id)
{
$modelName = 'App\Models\\'.$name;
$model = new $modelName;
if ($id === 'null') {
...
} else {
$data = $modelName::when(isset($model->getRelations()['customer']), function($query) {
return $query->with('customer');
})...
})->when(isset($model->getRelations()['rateTables']), function($query) {
return $query->with(array('rateTables' => function($q) {
$q->orderBy('cashStart', 'ASC');
}));
})->when(isset($model->getRelations()['rateRows']), function($query) {
return $query->with(array('rateRows' => function($q) {
$q->orderBy('rate', 'ASC');
}));
})->when(isset($model->getRelations()['rateRistournes']), function($query) {
return $query->with(array('rateRistournes' => function($q) {
$q->orderBy('ristourne', 'ASC');
}));
})->find($id);
}
return $data;
}
And there is the result into the console:
created_at:(...)
deleted_at:(...)
id:(...)
institution_id:(...)
name:(...)
rate_ristournes:Array(1)
rate_rows:Array(1)
rate_tables:Array(1)
The 3 last line should be:
rateRistournes:Array(1)
rateRows:Array(1)
rateTables:Array(1)
Is there a way to force laravel to keep the relation key as I wrote it?
Something under the hood change the name and I don't know how to bypass it.
Change $snakeAttributes:
class Rate extends Model
{
public static $snakeAttributes = false;
}

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

Categories