Laravel - Insert & delete rows upon updating - database

I have one-to-many Model relationship. While creating a new record, I can save as many rows as I want. But I want to add new row or delete saved row after Update operation. How would I do it?
Item Model
public function models() {
return $this->hasMany(Model::class, 'item_id');
}
Model Model
public function model()
{
return $this->belongsTo(Item::class, 'item_id');
}
Controller
Store
public function store(Request $request, Item $item)
{
$item = new Item;
$item->title = request('title');
if($item->save())
{
for ($i=0; $i < count(request('model_name')); ++$i)
{
$model = new Model;
$model->name = request('name')[$i];
$model->price = request('price')[$i];
}
return redirect()->back();
}
Update
public function update(Request $request, $id){
$item = Item::findOrFail($id);
$data = $request->all()
$models = Model::with(['model'])->where('item_id', $item->id)->get();
$i=0;
foreach($models as $new_model)
{
if (isset($model_name[$i])){
$new_model->sku = request('name')[$i];
$new_model->price= request('price')[$i];
$++i;
$shnp->models()->save($new_model);
}
}
$item->update($data);
}
Edit Form
Database Table

Related

Laravel Cart and controller

I am having issue with the route and controller.
The error code consist of sql column not found which is looking for column id from items table. Which im quite curious due to the differences with my migration.
CartController.php
namespace App\Http\Controllers;
use App\Cart;
use App\CartItem;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class CartController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function addItem ($itemNo){
$cart = Cart::where('user_id',Auth::user()->id)->first();
if(!$cart){
$cart = new Cart();
$cart->user_id=Auth::user()->id;
$cart->save();
}
$cartItem = new Cartitem();
$cartItem->itemNo=$itemNo;
$cartItem->cart_id= $cart->id;
$cartItem->save();
return redirect('/cart');
}
public function showCart(){
$cart = Cart::where('user_id',Auth::user()->id)->first();
if(!$cart){
$cart = new Cart();
$cart->user_id=Auth::user()->id;
$cart->save();
}
$items = $cart->cartItems;
$total=0;
foreach($items as $item){
$total+=$item->product->price;
}
return view('cart.view',['items'=>$items,'total'=>$total]);
}
public function removeItem($id){
CartItem::destroy($id);
return redirect('/cart');
}
}
ItemController.php
<?php
namespace App\Http\Controllers;
use App\Item;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
class ItemController extends Controller
{
public function index(){
$items = item::all();
return view('admin.items',['items' => $items]);
}
public function destroy($itemNo){
item::destroy($itemNo);
return redirect('/admin/items');
}
public function newItem(){
return view('admin.new');
}
public function add() {
$file = Request::file('file');
$extension = $file->getClientOriginalExtension();
Storage::disk('local')->put($file->getFilename().'.'.$extension, File::get($file));
$entry = new \App\File();
$entry->mime = $file->getClientMimeType();
$entry->original_filename = $file->getClientOriginalName();
$entry->filename = $file->getFilename().'.'.$extension;
$entry->save();
$Item = new Item();
$Item->file_id=$entry->id;
$Item->itemName =Request::input('name');
$Item->itemDescription =Request::input('description');
$Item->price =Request::input('price');
$Item->imageurl =Request::input('imageurl');
$Item->save();
return redirect('admin/items');
}
}

Retrive data based on pivot table in laravel

I have those tables in my database
Translation
id
translation_key_id
content
Language
id
code (it would be "eng" or "ger" or "fre")
translation_language
id
translation_id
language_id
Now the models are
class Language extends Eloquent {
protected $fillable = array('id','code');
protected $table = 'language';
private $rules = array();
public function translation()
{
return $this->belongsToMany('translation','language_translation');
}
}
class Translation extends Eloquent {
protected $fillable = array();
protected $table = 'translation';
private $rules = array();
public function language()
{
return $this->belongsToMany('language','language_translation');
}
}
Now i want to retrieve those data which have transkation_key_id = abc (as for example ) and also with code = "eng"
How can i do that?
First of all I don't see the need for pivot table here.
Show me why you need that, or change your relation to belongsTo. You can link translation with language using id (1) or code (2), which is unique obviously, right? So here it goes:
table translations: id, key, content, language_id (or language_code)
// Translation
public function language()
{
// option 1
return $this->belongsTo('Lanugage');
// or 2:
// return $this->belongsTo('Lanugage', 'language_code', 'code');
}t
then
// option 1
Translation::where('key', 'whatever')->whereHas('language', function ($q) {
$q->where('code', 'eng');
})->first();
// option 2, even easier w/o any join needed
Translation::where('key', 'whatever')->where('language_code', 'eng')->first();
You've built relationships incorrect
try this
class Language extends Eloquent {
protected $fillable = array('id','code');
protected $table = 'language';
private $rules = array();
public function translation()
{
return $this->belongsToMany('Translation','translation_language');
}
}
class Translation extends Eloquent {
protected $fillable = array();
protected $table = 'translation';
private $rules = array();
public function language()
{
return $this->belongsToMany('Language','translation_language');
}
}

Laravel Custom Pivot Table relationship and eager loading?

I am having problems with creating a schema / model for one of my projects and would like to get some help here.
I have 3 tables currently : accessories , products and a pivot table product_accessory
<?php
Schema::create('accessories', function(Blueprint $table)
{
$table->increments('id');
}
Schema::create('products', function(Blueprint $table)
{
$table->increments('id');
}
Schema::create('product_accessory', function(Blueprint $table)
{
$table->increments('id');
$table->integer('product_id')->unsigned();
$table->integer('accessory_id')->unsigned();
$table->foreign('product_id')->references('id')->on('products');
$table->foreign('accessory_id')->references('id')->on('accessories');
}
Now problem is I need to add another product type 'adaptors' that would ultimately depend on the pivot table relation, that is, adaptors need to relate to both a product and accessory...
UPDATE
Here is how my current product_accessory_adaptor table is
Schema::create('product_accessory_adaptor', function(Blueprint $table)
{
$table->increments('id');
$table->integer('product_accessory_id')->unsigned();
$table->foreign('product_accessory_id')->references('id')->on('product_accessory');
}
This way, i can have many adaptors relating to a product and accessory. My question is how do i model this relation in eloquent?
Here's what i have now:
Custom pivot model :
class ProductAccessory extends Pivot {
protected $table = 'product_accessory';
public function product()
{
return $this->belongsTo('Product');
}
public function accessory()
{
return $this->belongsTo('Accessory');
}
public function adaptors() {
return $this->hasMany('Adaptor', 'product_accessory_id');
}
}
Product and Accessory model
class Accessory extends Eloquent {
public function products()
{
return $this->belongsToMany('Product', 'product_accessory', 'accessory_id', 'product_id')->withPivot();
}
public function newPivot(Eloquent $parent, array $attributes, $table, $exists)
{
if ($parent instanceof Product) {
return new ProductAccessory($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
public function adaptors()
{
return $this->hasManyThrough('Adaptor', 'ProductAccessory', 'accessory_id', 'product_accessory_id');
}
}
class Product extends Eloquent {
public function accessories()
{
return $this->belongsToMany('Accessory', 'product_accessory', 'product_id', 'accessory_id')->withPivot();
}
public function newPivot(Eloquent $parent, array $attributes, $table, $exists)
{
if ($parent instanceof Accessory) {
return new ProductAccessory($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
public function adaptors()
{
return $this->hasManyThrough('Adaptor', 'ProductAccessory', 'product_id', 'product_accessory_id');
}
}
Adaptor model:
class Adaptor extends Eloquent {
protected $table = 'product_accessory_adaptor';
public function productAccessory() {
return $this->belongsTo('ProductAccessory');
}
}
Update
Now the schema and model is setup. However there are issues with using hasManyThrough relations. In addition, any way to do eager loading in this case for the pivot relation , i.e Adaptor?
Note
The error that occurs when i make a call to adaptors() on either the Product or Accessory model is
Argument 1 passed to Illuminate\Database\Eloquent\Relations\Pivot::__construct() must be an instance of Illuminate\Database\Eloquent\Model, none given, called in /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 872 and defined
That's your pivot:
<?php
use Illuminate\Database\Eloquent\Model as Eloquent;
// you don't need to call it ..Pivot, just my suggestion
class ProductAccessory extends Eloquent {
protected $table = 'product_accessory';
public function product()
{
return $this->belongsTo('Product');
}
public function accessory()
{
return $this->belongsTo('Accessory');
}
public function adaptors()
{
return $this->hasMany('Adaptor', 'product_accessory_id');
}
}
// Product model
public function adaptors()
{
return $this->hasManyThrough(
'Adaptor', 'ProductAccessoryPivot', 'product_id', 'product_accessory_id'
);
}
// Accessory model
public function adaptors()
{
return $this->hasManyThrough(
'Adaptor', 'ProductAccessoryPivot', 'accessory_id', 'product_accessory_id'
);
}
Now example usage:
$product = Product::first();
$product->adaptors; // collection of all adaptors for given product
$product->adaptors->first()->accessory; // accessory for single adaptor
$product->accessories; // collection of accessories, each with your custom pivot, so:
$product->accessories->first()->adaptors; // collection of adaptors for given product-accessory pair
... and more, try it

wordpress query num_rows won't return value

I try to get number of rows per query in my wordpress Class but I get each time null, what is wrong with the following
class MyClass{
private $wpdb;
private $query;
public function __construct(){
global $wpdb;
this->wpdb = &$wpdb;
}
public function build_query(){
//dynamic query will be build here, example
$this->query = 'SELECT id,name From my_table';
}
public function get_display_result(){
$res = $this->wpdb->get_results($this->query, ARRAY_A);
return $res;
}
public function get_total_results(){
$res = $this->wpdb->get_results($this->query);
$nr = $res->num_rows;
var_dump($nr);// I get NULL
exit();
return $res;
}
}
You have to use $wpdb to get number of rows
$this->wpdb->num_rows;

PHP Queue class issue

I'm trying to write a method for a class Queue that inverts the whole Queue. After running the program, it gives the follow problem:
Cannot use object of type Queue as array on line echo($i.".
".$this->kolejka[$i-1]."<br>");
Apparently when he is trying to use printOut method again on the inverted Queue. Please help!
Please don't laugh (too hard) as I tried many things to make this work and I'm lost.
Here is the whole code:
<?php
class Queue
{
private $Queue = array(); //Init
public function clear() //Clears the Queue
{
$this->Queue = array();
}
public function isMember($item) //Returns True if element is in the Queue
{
foreach($this->Queue as $x)
{
if($item === $x)
{
return true;
}
}
return false;
}
public function remove() //Removes first element
{
return array_shift($this->Queue);
}
public function add($item) //Adds element to the end
{
$this->Queue[] = $item;
}
public function first() //Returns the first element
{
return current($this->Queue);
}
public function printOut() //Writes down in order all the elements
{
for($i=1;$i < count($this->Queue)+1;$i++)
{
echo($i.". ".$this->Queue[$i-1]."<br>");
}
}
public function length() //Returnts length
{
return count($this->Queue);
}
public function invert() //Reverts the Queue
{
$newQueue = new Queue();
for ($i = $this->length() - 1;$i>=0;$i--)
{
$newQueue->add($this->first());
$this->remove();
}
$this->Queue = $newQueue;
}
}
$kolej = new Queue();
$kolej->add("Apple");
$kolej->add("Orange");
$kolej->add("Banana");
$kolej->add("Mandarin");
$kolej->add("Raspberry");
echo $kolej->first()."<br>";
$kolej->remove();
echo $kolej->first()."<br>";
echo $kolej->isMember("Apple")."<br>";
echo $kolej->isMember("Orange")."<br>";
$kolej->printOut();
echo "Currently Queue is of length ".$kolej->length()."<br>";
$kolej->invert();
$kolej->printOut();
?>
your invert() function is doing the wrong thing. $this->Queue is supposed to be an array:
private $Queue = array(); //Init
, but at the end of the function you are setting it to an object (named $newQueue):
public function invert() //Reverts the Queue
{
$newQueue = new Queue();
for ($i = $this->length() - 1;$i>=0;$i--)
{
$newQueue->add($this->first());
$this->remove();
}
$this->Queue = $newQueue;
}
You can solve this in one of two ways:
set $this->Queue to $newQueue->Queue (you probably have to make it a non-private variable)
learn how to invert an array in place instead of creating a temporary array
Here is solid solution for the invert method. I hope this helps.
//Reverts the Queue
public function invert() {
$newQueue = array();
for ($i = 0; $i < count($this->Queue) + 1; $i++) {
$newQueue[$i] = $this->Queue[count($this->Queue) - 1 - $i];
echo $newQueue[$i] . '<br/>';
}
}

Resources