Laravel 5.2 Update with foreign key - laravel

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.

Related

Laravel 5.4 unable to access data through foreign key in blade

I m new to laravel, and have set up a couple of models and views etc. Anyways, what i am trying to do is, I have a users model, and a teams model. The field 'id' is foreign key for users' team_id.
The user can join any team and the team he joins, its id will be stored in user's 'team_id'.
What I am trying to do it, using the team_id field to get data from the teams model, like the team name and display it on my blade view.
Here is my code for Users model:
protected $fillable = ['name',
'email',
'password',
'date_of_birth',
'team_id', /*references id in teams model*/
'matches_played',
'goals_scored',
'preferred_position',
'phone_number',
'role',
'ban_status',
'team_captain'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function Teams(){
return $this->belongsTo('App\Teams', 'team_id');
}
}
This is my code for teams model:
`protected $primaryKey = 'id';
protected $fillable = ['team_name', 'matches_played',
'matches_lost', 'goals_scored', 'goals_conceded',
'captain_name'];
public function User(){
return $this->hasMany('App\User','id');
}
`
public function showMembers(){
$users = User::with(array('Teams'))->get();
return view('admin.members')->with('users', $users);
}
`
`
and this is how i am trying to show it in blade:
{{$user->team_id->team_name}}
But instead of displaying it, i keep on getting:
Trying to get property of non-object (View: D:\Code\PHP\Code\PlayOn\resources\views\admin\members.blade.php)
Any help would be appreciated!
There are a couple of things you are doing wrong here.
First, to eager load a relationship, in this case, the teams' relationship, this is the way to do it:
$users = User::with('Teams')->get();
Finally, to loop through the Collection, you would need to do something like this:
#foreach($users as $user)
{{ $user->Teams->team_name }}
#endforeach

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 : Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails - Many to Many relationship

I know there's a bunch of problems asked about laravel integrity constraint violation, but none of them are Many to Many relationship, which is my case. Basically I have a table Hobi (hobby) and table Siswa (student), and the relationship is many to many since a student can have many hobbies and a hobby can be favored by many students. So here is the code :
This is my model Hobi :
namespace App;
use Illuminate\Database\Eloquent\Model;
class Hobi extends Model
{
protected $table = 'hobi';
protected $fillable = [
'nama_hobi',
];
public function siswa(){
return $this->belongsToMany('App\Siswa', 'hobi_siswa', 'id_hobi', 'id_siswa');
}
}
model Siswa :
namespace App;
use Illuminate\Database\Eloquent\Model;
class Siswa extends Model
{
protected $table = 'siswa';
protected $fillable = [
'nisn',
'nama_siswa',
'tgl_lahir',
'jns_klmin',
'id_kelas',
'id_hobi',
];
public function hobi(){
return $this->belongsToMany('App\Hobi', 'hobi_siswa', 'id_siswa', 'id_hobi')->withTimeStamps();
}
}
A piece of form view code which contained Hobi :
#if($errors->any())
<div class="form-group {{$errors->has('hobi') ? 'has-error' : 'has-success'}}">
#else
<div class="form-group">
#endif
{!! Form::label('hobi', 'Hobi:', ['class'=>'control-label']) !!}
#if(count($hobi_list) > 0)
#foreach($hobi_list as $key => $value)
<div class="checkbox">
<label>{!! Form::checkbox('hobi[]', $value, null) !!}{{$value}}</label>
</div>
#endforeach
#else
<p>Tidak ada pilihan hobi.</p>
#endif
</div>
And finally the controller :
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Siswa;
use App\Telepon;
use App\Kelas;
use App\Hobi;
use Validator;
class SiswaCont extends Controller
{
public function siswa(){
$siswa_list = Siswa::orderBy('nama_siswa', 'asc')->paginate(10);
$jmlh_siswa = Siswa::count();
return view('siswa.ssw', compact('siswa_list', 'jmlh_siswa'));
}
public function create(){
$kelas_list = Kelas::lists('nama_kelas', 'id');
$hobi_list = Hobi::lists('nama_hobi', 'id');
return view('siswa.create', compact('kelas_list', 'hobi_list'));
}
public function store(Request $request){
$input = $request->all();
$validator = Validator::make($input, [
'nisn'=>'required|string|size:4|unique:siswa,nisn',
'nama_siswa'=>'required|string|max:30',
'tgl_lahir'=>'required|date',
'jns_klmin'=>'required|in:L,P',
no_telepon'=>'sometimes|numeric|digits_between:10,15|unique:telepon,no_telepon',
'id_kelas'=>'required',
]);
if ($validator->fails()) {
return redirect('siswa/create')->withInput()- >withErrors($validator);
}
$siswa = Siswa::create($input);
$siswa->hobi()->attach($request->input('hobi'));
return redirect('siswa');
}
}
I'm using pivot table hobi_siswa to contain id_siswa and id_hobi, creating a bridge. Hobi itself in form view is checkbox modeled. The problem is constraint, data Siswa for another column (nisn, nama_siswa, telepon, etc.) are saved, but Hobi not. Any help appreciated.
Use sync method instead of attach which accepts an array.
From the Docs
The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table.
For example:
$user->roles()->sync([1, 2, 3]);

problems to add data in pivot table laravel 5.1

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>

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