Laravel 4 one to many Relationship insertion - php

I'm using Laravel 4. I have a table called shipment and it related with many Items.
Here my code
Shipment controll
class ShipmentControl extends BaseController{
public function init(){
$places=Places::lists('place','id');
return View::make('Shipment.shipmentadd')
->with('places',$places);
}
public function save(){
//echo "Im HERE";
//$shipment=Input::all();
$rules=array(
'initials'=>'required',
'surname'=>'required',
'rece_initials'=>'required',
'rece_surname'=>'required',
'email'=>'email',
'rece_email'=>'email',
'nort_email'=>'email',
);
$v=Validator::make(Input::all(),$rules);
if($v->fails()){
return Redirect::to('shipment')->withInput()->withErrors($v);
}
$shipment=new Shipment;
$shipment->initials=Input::get('initials',null);
$shipment->surname=Input::get('surname',null);
$shipment->addrsss=Input::get('address',null);
$shipment->email=Input::get('email',null);
$shipment->telephone=Input::get('telephone',null);
$shipment->reciver_initials=Input::get('rece_initials',null);
$shipment->reciver_surname=Input::get('rece_initials',null);
$shipment->reciver_address=Input::get('rece_address',null);
$shipment->reciver_email=Input::get('rece_email',null);
$shipment->reciver_telephone=Input::get('rece_telephone',null);
$shipment->notfy_name=Input::get('nort_name',null);
$shipment->notify_mail=Input::get('nort_email',null);
$shipment->notify_telephone=Input::get('nort_telephone',null);
$shipment->port_of_loading=Input::get('port_of_loading',null);
$shipment->vessle=Input::get('vessel',null);
$shipment->eta=Input::get('eta',null);
$shipment->place_of_collection=Input::get('place',null);
if($shipment->save()){
$items=Session::get('items');
foreach ($items as $value) {
# code...
//array_unshift($value,$shipment->id());
$Items=new Items;
$Items->shipment_id=$shipment->id();
$Items->type=$value['type'];
$Items->qty=$value['qty'];
$Items->height=$value['height'];
$Items->weight=$value['width'];
$Items->lenght=$value['length'];
$Items->save();
}
}
Session::flush();
}
}
Shipment Model
lass Shipment extends Eloquent{
protected $table = 'shipment';
public $timestamps = false;
public function places(){
return $this->belongsTo('Places','place_of_collection');
}
public function items(){
return $this->hasMany('items','shipment_id');
}
}
and Here Item Model
class Items extends Eloquent{
protected $table = 'items';
public $timestamps = false;
public function shipment(){
return $this->belongsTo('Shipment','shipment_id');
}
}
I'm Using a Session to keep items. So when I try to insert details It show me this error
Call to undefined method Illuminate\Database\Query\Builder::id()
But the shipping details are added to the table.I googled it but i can't find the Solution. What is this Build::id is..?

Related

Laravel Polymorphic Relations returns NULL

I've read many posts about this issue but none of them works for me. I have a 'ISA' relationship in my database. A person can be either a Patient or a Nurse:
class Person extends Model
{
protected $table = 'persons';
public function commentable()
{
return $this->morphTo();
}
}
class Patient extends Model
{
public function persons()
{
return $this->morphMany('App\Person', 'commentable');
}
}
class Nurse extends Model
{
public function persons()
{
return $this->morphMany('App\Person', 'commentable');
}
}
This is my tables and the data inside them:
And this is my Route:
Route::get('person', function () {
$person = Person::find(1)->commentable();
return json_decode(json_encode($person), true);
});
I get an empty array!
You have to access the relationship as a property:
$person = Person::find(1)->commentable;

Laravel 5.6: Relationship with multiple tables and conditions

Consider I'm a hotel owner, and I have to know the bookings related to my hotel.
I need all bookings that which associated with my hotel.
Is there any eloquent functions to join? How?
How to get bookings of a hotel with owner(userid) with using eloquent relationship functions?
Hotel.php
class Hotel extends Model
{
public function userId(){
return $this->belongsTo(User::class,'user_id');
}
public function rooms(){
return $this->hasMany(Room::class,'hotel_id','id');
}
}
Room.php
class Room extends Model
{
public function hotelId(){
return $this->belongsTo(Hotel::class,'hotel_id');
}
public function bookings(){
return $this->hasMany(Booking::class,'room_id','id');
}
}
User.php
class User extends Model
{
public function hotels(){
return $this->hasMany(Hotel::class,'user_id','id');
}
}
Below code add in your respective controller.
$user = \App\User::find(Auth::id());
$hotels = $user->hotels;
foreach ($hotels as $hotel) {
$rooms = $hotel->rooms;
foreach ($rooms as $room) {
print_r($room->bookings);
}
}
Define the relationship with user in model
class Booking extends Model{
/**
* Get the user that owns the booking.
*/
public function owner()
{
return $this->belongsTo(App\User::class,'user_id,'id');
}
}
Then in your controller
$bookings = Booking::with('owner')->all(); // or get() or whatever to get
the booking list
foreach($bookings as $booking){
echo $booking->user->name; // you have access to owner fields
}
Finally i found this.
Booking model
public function room( )
{ return $this->belongsTo('App\room');
}
public function hotel( )
{
return $this->room()->with(['hotel'=> function($query){
$query->with('user');
}]);
}
BookingController
public function owner(Booking $booking ) {
return $booking->with('hotel')->get()
Next thing is Filter with owner

Laravel 5.2 Nested Eloquent relationships

I have a User which is of type Player and has several Equipments
I want to request a piece of Equipment and see if the User is it's owner before returning it to the user. If they do not own it they will get an unauthorized response
Here are the relationships I have for the models:
App\User.php
class User extends Authenticatable
{
protected $table = 'user';
public function player()
{
return $this->hasOne(Player::class);
}
}
App\Player.php
class Player extends Model
{
protected $table = 'player';
public function equipment()
{
return $this->hasMany(Equipment::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
App\Equipment.php
class Equipment extends Model
{
protected $table = 'equipement';
public function player()
{
return $this->belongsTo(Player::class);
}
}
EquipmentController.php
With my attempt which is working... just very ugly.
class EquipmentController extends Controller
{
public function show($id)
{
$equipment = Equipment::find($id);
if ( ! $equipment ) {
return 'Equipment does not exist');
}
// my attempt
$test = Equipment::with('player.user')->findOrFail($id);
if ($test->toArray()['player']['user']['id'] != Auth::user()->id){
return 'Unauthorized';
}
//
return $equipment;
}
}
Is there a neater way to do this?
I want something readable in the controller like:
if(!$equipment->ownedBy(Auth::user())){
return 'Unauthorized';
}
Or something similarly as readable.
And once the relationship is found, I'm not sure where the logic should be placed. Should it be in the Equipment model?
Any help would be much appreciated!
In your Equipment model:
public function authorized()
{
return ($this->player->user->id == auth()->user()->id())
}
Then from your controller, try:
$equipment->authorized() //returns true or false

eloquent boot not firing only for one class

I'm using eloquent for a project and I would like to delete articles. The problem is that the database is complicated. There are articles, that have article_lvl1 and article_lvl1 have article_lvl2. When I delete an article the event functions work fine :
<?php
namespace app\model;
class Article extends \Illuminate\Database\Eloquent\Model
{
public static function boot()
{
parent::boot();
// cause a delete of a product to cascade to children so they are also deleted
static::deleting(function($article)
{
$article->ArticleNiveau1()->delete();
$article->ArticleNiveau2()->delete();
});
}
public function ArticleNiveau1()
{
return $this->hasMany('app\model\ArticleNiveau1', 'id_article');
}
public function ArticleNiveau2()
{
return $this->hasMany('app\model\ArticleNiveau2', 'id_article');
}
protected $table = 'Article';
public $timestamps = false;
protected $primaryKey = 'id_article';
}
But an article can also have article_Informations, which can have article_Date. My problem is that everything in the boot functions executes fine on delete, but not the article_Date. Here is the code :
<?php
namespace app\model;
class Article_Informations extends \Illuminate\Database\Eloquent\Model
{
public function Article()
{
return $this->belongsTo('app\model\Article', 'id_article');
}
public function ArticleNiveau1()
{
return $this->belongsTo('app\model\ArticleNiveau1', 'id_nv1');
}
public function ArticleNiveau2()
{
return $this->belongsTo('app\model\ArticleNiveau2', 'id_nv2');
}
public function Article_Date()
{
return $this->hasMany('app\model\Article_Date', 'id_info');
}
public static function boot()
{
parent::boot();
// cause a delete of a product to cascade to children so they are also deleted
static::deleting(function($info)
{
$info->Article_Date()->delete();
});
}
protected $table = 'Article_Informations';
public $timestamps = false;
protected $primaryKey = 'id_info';
}
I don't know why, it's the only event that is not fired on delete.
Can someone explain me ?

Laravel model object chaining

For some reason, I cannot chain model objects. I'm trying to eager load 'Location' for an 'Order' and would prefer the logic to be contained in the models themselves. But past one chain, it does not work.
class Order extends Eloquent {
protected $table = 'orders';
public function customer() {
return $this->belongsTo('Customer');
public function location() {
return $this->customer()->location(); // this does not work
}
}
class Customer extends Eloquent {
protected $table = 'customers';
public function user() {
return $this->belongsTo('User');
}
public function orders() {
return $this->hasMany('Order');
}
public function location() {
return $this->user()->location();
// return $this->user(); // WORKS!!
}
}
class User extends Eloquent {
protected $table = 'users';
public function locations() {
return $this->hasMany('Location');
}
public function location() {
return $this->locations()->first();
}
}
I eventually want to do this:
class ChefController extends BaseController {
public function get_orders() {
$chef = $this->get_user_chef(); // this already works
return $chef->orders()->with('location')->get(); // does not work
}
}
Try to reference relation (user table) by adding user_id as second argument, like this:
public function user() {
return $this->belongsTo('User',"user_id");
}
Maybe you called that id field different, but you know what I mean.

Categories