problems to add data in pivot table laravel 5.1 - laravel-5

I hope you are fine.
I have a problem with a pivot table in laravel 5.1
I want it that several products are inserted into this table , which have made ​​relations with two more tables . The problem is that inserts well ids products, but the extra fields such as quantity and price would not add them all , that is , I only adds a value of one product, do not know if I explained well . Of all forms attached photos of models , drivers and user view with the database .
Is there something missing I do? Please if you can help me .
Beforehand thank you very much!!
PD: Sorry my english. I´m from latin america and I don´t speak english very well.
http://fotos.subefotos.com/4e0348b36bf41fc1051873d4778193afo.png
http://s32.postimg.org/w4gp59jqt/foto_2.png
Bill model
class Bill extends Model
{
protected $table = 'bills';
protected $fillable = ['date_at'];
}
public function products()
{
return $this->belongsToMany('App\Product','bill_product','product_id', 'bill_id','dquantity','dprice')->withTimestamps();
}
}
Product Model
class Product extends Model
{
protected $table = 'products';
protected $fillable = ['name', 'price','stock'];
}
public function bills()
{
return $this->belongsToMany('App\Bill','bill_product','bill_id', 'product_id','dquantity','dprice')->withTimestamps();
}
Controller
public function store(Request $request)
{
$fac = Bill::create($request->all());
//Obtener ids de lineas de productos
$productIds = $request->input('product_id');
$cant= $request->input('dquantity');
$prec=$request->input('dprice');
$fac->products()->attach($productIds , ['dprice' => $prec,'dquantity' => $cant]);
}
View
<td>
{!!Form::select('product_id[]',$produ,null,['class'=>'form-control'])!!}
</td>
<td width="20%">
{!!Form::text('dquantity', null,['class'=>'form-control','id'=>'cantidad'])!!}
</td>
{!!Form::text('dprice', null,['class'=>'form-control', 'id'=>'precio'])!!}
</td>

Related

Trying to get property 'name' of non-object?

Hi Guys i am new to laravel and i am trying to retrieve category names for each formation and i am getting this error
Trying to get property 'name' of non-object (0)
The "name" i am trying to retrieve is the name of category that my formation belongs to.
This is My Category Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
function formations()
{
return $this->hasMany('App\Formation');
}
protected $fillable =['name','description'];
}
And This is My Formation Model
class Formation extends Model
{
function category()
{
return $this->belongsTo('App\Category',"category_id");
}
protected $fillable =['name','price','durations','category_id'];
}
And here is my view page where i am trying to retrieve the category name
#foreach($formations as $formation)
<td>{{$formation->name}}</td>
<td>{{$formation->price}}</td>
<td>{{$formation->category->name}}</td>
td>{{$formation->durations}}</td>
#endforeach
This is My Controller
public function index()
{
//$formations = Formation::all();
$formations = Formation::with('category')->paginate('4');
$categories = Category::all();
return view('formation.index',compact('categories','formations'));
}
Any Suggestion about where i might be wrong ? And thanks in Advance !
This error usually comes when you have removed one or more row from database, but trying to access that row with an id. Make sure that you have all the category in the category table with the id which is mentioned in the formation table category_id field.
In your view
#foreach($formations as $formation)
<td>{{$formation->name}}</td>
<td>{{$formation->price}}</td>
<td> {{ $formation->categories()->pluck('name')->implode(' ') }}</td>
<td>{{$formation->durations}}</td>
#endforeach
Try changing the relationship
class Formation extends Model
{
function category()
{
return $this->belongsTo('App\Category',"id","category_id"); //if your categories id is id
}
protected $fillable =['name','price','durations','category_id'];
}
In your view
#foreach($formations as $formation)
<td>{{$formation->name}}</td>
<td>{{$formation->price}}</td>
<td>{{$formation->category->name}}</td>
<td>{{$formation->durations}}</td>
#endforeach
The Problem was that i have deleted a row from my category table in database that's why the name wasn't recognized.

How can I sort a table in a many to many relationship by a pivot table column?

I want to sort a table of teachers by the school they belong to. The name of the school is a column in the pivot table.
I have a table of teachers, a table of schools and a pivot table. The teacher's table has ID, lastname, firstname. The schools' table has ID, school_name. The pivot table ('teacher_school') has ID, school_ID, teacher_ID. I know how to sort the teachers' table by teachers' lastname but no idea how to sort teachers by its school name.
1.My teacher model:
class Teacher extends Model
{
public $table = "teachers";
public $primaryKey = "ID";
public $timestamps = false;
public $guarded = [];
public function schools() {
return $this->belongsToMany("App\School", "teacher_school",
"teacher_ID", "school_ID");
}
}
My school model:
class School extends Model
{
public $table = "schools";
public $primaryKey = "ID";
public $timestamps = false;
public $guarded = [];
public function teachers() {
return $this->belongsToMany("App\Teacher", "teacher_school", "school_ID", "teacher_ID");
}
}
My current teachers' controller (which sorts teachers by "ID", not by their school name):
public function listBySchool(Request $req) {
$teachers = Teacher::orderBy('ID')->paginate(200);
return view("listTeachersBySchool", compact("teachers"));
}
My view:
#foreach ($teachers as $teacher)
<tr>
<td>{{$teacher["ID"]}}</td>
<td>{{$teacher["lastname"]}}</td>
<td>{{$teacher["firstname"]}}</td>
<td>
#foreach ($teacher->schools as $school)
{{$school["school_name"]}}
#endforeach
</td>
</tr>
#endforeach
Please help me to make my view display teachers ordered by their school names. ¡Thanks a ton!
I assume you want to sort the teachers by the school name from schools table. Because the pivot table mentioned above doesn't have the school name.
I recommend using a multiple-join query to achieve what you want.
Teacher::select('teachers.*')
->join('teacher_school', 'teachers.id', '=', 'teacher_school.teacher_id')
->join('schools', 'teacher_school.school_id', '=', 'schools.id')
->orderBy('schools.school_name')
->distinct();

BelongsToMany of Laravel 5.4 does not work

I am creating a table where it displays a list of requests, I have a relation between the ID's 'erp_createdid' and 'erp_productid'. To display the name of the products, I created a belongsToMany, in which I specify my two 'ID's'.
Order model
class Order extends Model
{
protected $table = 'erp_order';
protected $fillable = ['erp_createdid'];
protected $primaryKey = 'erp_orderid';
public function description()
{
return $this->belongsToMany('App\Description','erp_order_product', 'erp_createdid', 'erp_productid');
}
}
Description Model
class Description extends Model
{
protected $table = 'erp_product_description';
protected $primaryKey = 'erp_productid';
protected $fillable = ['erp_name'];
public $timestamps = false;
public function order()
{
return $this->belongsToMany('App\Order', 'erp_order_product', 'erp_createdid', 'erp_productid');
}
Table
<td>#foreach($orders->description as $des)
{{$des->erp_name}}
#endforeach
</td>
But the values in the table are not displayed, any suggestions?
I think you have the parameters on Order's belongsToMany in an incorrect order.
Try this:
public function description()
{
return $this->belongsToMany('App\Description','erp_order_product', 'erp_productid', 'erp_createdid');
}
Also try updating your foreach like this:
Oh OK, try this:
#foreach($orders as $order)
#foreach($order->description as $description)
{{ $description->erp_name }}
#endforeach
#endforeach

Laravel 5.2 Update with foreign key

hello i've been working on a laravel project lately, and i've wanted to be able to update my records that have foreign keys in them. i've succesfully been able to update records in tables that dont have a foreign key but for some reason my table with a foreign key doesn't want to update. when i var_dump($voorraad) i get the new value on my screen but it doesn't update into the database. I have the same code for my Product table and Location table and there it works completely fine.
My Controller:
public function update(Request $request, $id)
{
//voorraad = stock in dutch
//Product_id = foreign key from the table products
//locatie_Id = foreign key from the tabe locations
//aantal = ammount of a certain product
$voorraad = Voorraad::FindOrFail($id);
$voorraad->fill($request->only('aantal', 'Product_id', 'locatie_Id'));
$voorraad->save();
return redirect(route('voorraad.index'));
}
My voorraad model
class Voorraad extends Model
{
//aantal is the ammount
protected $fillable = ['aantal', 'Product_id', 'locatie_Id'];
protected $table = 'voorraad';
public function products()
{
return $this->belongsTo('App\Product', 'Product_id');
}
public function locaties()
{
return $this->belongsTo('App\Locatie', 'locatie_Id');
}
My Product Model
class Product extends Model
{
//inkoopprijs = sell price
//verkoop prijs = buy price
//naam = product name
protected $fillable = ['naam', 'inkoopprijs', 'verkoopprijs','created_at', 'updated_at'];
protected $table = 'product';
}
My Location Model:
class Locatie extends Model
{
protected $fillable = ['naam'];
protected $table = 'locatie';
}
My edit form:
{!! Form::model($voorraad,['action' => ['VoorraadsController#update', $voorraad->Id], 'method' => 'PATCH'])!!}
{!! Form::label('aantal', 'aantal:') !!}
{!! Form::text('aantal')!!}<br>
{!! Form::label('Product_id', 'product:') !!}
{!! Form::select('Product_id', $products)!!}<br>
{!! Form::label('locatie_Id', 'locatie:') !!}
{!! Form::select('locatie_Id', $locaties)!!} <br>
{!! Form::submit('edit') !!}
Gyazo of Var_dump($voorraad): https://gyazo.com/109d54e2bb7a91bbb8b047611e66dbe0
gyazo of var_dump($request):https://gyazo.com/8437ee90881ba38a039b5b583f8296a5
If there is any information missing just let me know and i'll add it
You can update the model and associate it with the Product and Location it belongs to like this:
$voorraad = Voorraad::findOrFail($id);
$product = Product::findOrFail($request->input('Product_id'));
$location = Location::findOrFail($request->input('locatie_Id'));
$voorraad->aantal = $request->input('aantal');
$voorraad->save();
$product->voorraad()->associate($voorraad);
$location->voorraad()->associate($voorraad);
Of course you have to use the proper names for your models.

Laravel Category Model Relationships

I have the following table structure in my database.
Table Name: tiles
Columns: id, tile_name, tile_thumb, tile_snippet
Table Name: tags
Columns: id, tag_title
Table Name: tile_tags
Columns: id, tile_id, tag_id
Models:
Tile, Tag, TileTag
In my main model class for entries I am specifying the following relationship to a model called TileTag which is a pivot table.
<?php namespace Tiles;
use Illuminate\Database\Eloquent\Model;
class Tile extends Model {
protected $table = 'tiles';
public function tags() {
return $this->belongsTo('Tiles\TileTag');
}
}
During my foreach loop it returns the tile_name and any other columns from my table, except the ones joined by the relatipnship.
#foreach($tiles as $tile)
<a href="tile/{{$tile->tile_name}}">
<li class="col-md-4 mix" data-category="{{ $tile->tags->tag_title }}">
{!! HTML::image($tile->tile_thumb, null, array('class' => 'img-responsive')) !!}
</li>
</a>
#endforeach
How can I get my categories/tags linked to my primary entries when they are sorted during each loop?
I try returning the data during the loop by {{ $tile->tags->tag_title }} but it returns an empty string.
Controller Method:
class TileController extends Controller {
/**
* Display a listing of tiles from the database.
*
* #return Response
*/
public function index() {
// Get tile data from the model
$tiles = \Tiles\Tile::all();
return view('pages.index', compact('tiles'));
}
Returned Array:
I think that you don't have to create a model for Tile_Tag. Laravel can handle ManyToMany relationships out of the box (I suppose that this is the type of the relationship because you use pivot table). Your models should be
class Tile extends Model {
protected $table = 'tiles';
public function tags() {
return $this->belongsToMany('Tiles\Tag');
}
}
and
class Tag extends Model {
protected $table = 'tags';
public function tiles() {
return $this->belongsToMany('Tiles\Tile');
}
}
Laravel will know that you have a pivot table named "tag_tile" with columns "tag_id" and "tile_id". Check the relevant documentation here
Then you can iterate through tags collection for each tile like this
#foreach ($tiles as $tile)
{!!$tile->tile_name!!}
#foreach ($tile->tag as $tag)
{!!$tag->tag_title!!}
#endforeach
#endforeach
Hope it helps.

Resources