Laravel Eloquent Eager Loading multiple relationships with pagination - php

I have a site running Laravel 4.2 that I am working on right now, the problem is that I have a single model for orders and another child model for items that belong to the order. The items also have a child model for size information and image information.
I have my query:
$orders = Auth::user()->orders()->with('items','items.size','items.image')->get()->toArray();
This returns what I am expecting, but I want to have the results paginated using Laravel's pagination. I had expected this to work:
$orders = Auth::user()->orders()->with('items','items.size','items.image')->paginate( 10 );
This returns a blank white page and a 500 error and for the life of me I can't figure out how to get this to work correctly.
Here are my various models: User.php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
protected $fillable = array( 'first_name', 'last_name', 'address', 'city', 'state', 'zip', 'lat', 'lng', 'email', 'phone', 'password', 'hash', 'type', 'blocked', 'created_at', 'updated_at', 'deleted_at' );
public function setPasswordAttribute( $value ) {
return $this -> attributes['password'] = Hash::make( $value );
}
public function projects() {
return $this -> belongsToMany('Project');
}
public function orders() {
return $this->hasMany('PrintOrder');
}
public function bookings() {
return $this -> belongsToMany('Booking');
}
}
PrintOrder.php
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class PrintOrder extends Eloquent {
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'print_orders';
protected $fillable = array( 'project_id', 'user_id', 'status', 'created_at', 'updated_at', 'deleted_at' );
public function items() {
return $this->hasMany('PrintOrderItem');
}
}
PrintOrderItem.php
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class PrintOrderItem extends Eloquent {
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'print_order_items';
protected $fillable = array( 'print_order_id', 'upload_id', 'size_id', 'quantity', 'created_at', 'updated_at', 'deleted_at' );
public function image() {
return $this->hasOne('Upload','id');
}
public function size() {
return $this->hasOne('PrintSize', 'id');
}
}
Upload.php
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Upload extends Eloquent {
use SoftDeletingTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'uploads';
protected $fillable = array( 'user_id', 'project_id', 'thumbnail', 'small','medium','large','original','title', 'description','keywords', 'file_type','file_size','file_extension','created_at', 'updated_at', 'deleted_at' );
protected $dates = ['deleted_at'];
public function categories() {
return $this->belongsToMany('UploadCategory', 'upload_image_categorys');
}
}
PrintSize.php
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class PrintSize extends Eloquent {
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'print_sizes';
protected $fillable = array( 'title', 'description', 'cost_actual', 'cost_client', 'status', 'created_at', 'updated_at', 'deleted_at' );
}

Related

Laravel - can a method on Eloquent model class ignore Trait?

I have a User Model class that uses UserHasTeams trait, and this User class has a relationship method called projects. Now my question is, is it possible that somehow this projects method ignores the trait UserHasTeams because it appends the team_id in the where clause of my eloquent query, which I don't want. Here is the code
<?php
namespace App;
class User extends Authenticatable
{
use Notifiable, Billable, UserHasTeams;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'company_id', 'role', 'status', 'trial_ends_at',
'address_line_1', 'address_line_2', 'city', 'state', 'zipcode', 'country_id'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
protected $dates = ['trial_ends_at'];
public function company() {
return $this->belongsTo(Company::class);
}
public function projects() {
return $this->hasMany(Project::class);
}
}
whenever I use Project::all(), it appends team_id which is accepted but for some instances, I don't want this projects method to use Trait, is It possible? If yes, how?
Thanks in advance.

how can i handle this error : Undefined offset: 0

I'm producing an online school platform and in part of it student can see it's classes with their informations..but the related function return this error : Undefined offset: 0 (View: C:\xampp\htdocs\OnlineSchool\resources\views\admin\student\ClassReport.blade.php)
there are some relations between models
My Models:
USER(students and teachers) ، LEVEL(level of classes) ، Classroom.
=> there is a many to many relation between student and classroom (pivot table)
please save me from this stupid error
user:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','image','level','code_meli',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function classroom(){
return $this->hasMany (classroom::class);
}
public function ClassRoomStudent(){
return $this->belongsToMany (classroom::class ,'classroom_user','user_id','classroom_id');
}
}
classroom:
class classroom extends Model
{
protected $fillable = [
'title', 'teacher_id', 'level_id','day','time','price',
];
public function Student(){
return $this->belongsToMany (user::class ,'classroom_user','classroom_id','user_id');
}
public function level(){
return $this->belongsTo (level::class );
}
public function teacher(){
return $this->belongsTo (user::class );
}
}
level :
class level extends Model
{
protected $fillable = [
'title',
];
public function classroom(){
return $this->hasMany (classroom::class);
}
public function exam(){
return $this->hasMany (exam::class);
}
}
and my function in controller:
public function MyClasses(){
$student_id=auth ()->user ()->id;
$classrooms=classroom::with ('level','teacher','factor')->wherehas('student',function ($q) use($student_id){
$q->where('id',$student_id);
})->get();
return view ('admin.student.ClassReport',compact ('classrooms','student_id'));
}
at the end .. my blade:
#foreach($classrooms as $class)
<tr>
<td>{{$i++}}</td>
<td>{{$class->title}}</td>
<td>{{$class->teacher[0]->name}}</td>
.
.
.
.
</tr>
#endforeach
The Classroom belongs to only one teacher, no need to use de zero index, just type $class->teacher->name

How to chain 3 laravel nested models

I am trying to chain 3 models together parent->child->child of child. So I can access it in an eloquent statement.
Parent Model:
class CertificationType extends Model
{
use SoftDeletes;
public $timestamps = true;
protected $table = 'certification_type';
protected $dates = ['deleted_at'];
protected $fillable = array('certification_type_name', 'fa_code', 'icon_image');
protected $hidden = ['created_at', 'updated_at',];
public function certification_type()
{
return $this->hasMany('App\Certification');
}
}
Child Model
class Certification extends Model
{
protected $table = 'certification';
public $timestamps = true;
use SoftDeletes;
protected $dates = ['deleted_at'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = array('certification_type_id', 'certification_name', 'certication_date', 'certification_license_number', 'certification_course_length', 'certification_course_description', 'certification_course_topics_list_id');
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'created_at', 'updated_at',
];
public function certification_type()
{
return $this->belongsTo('App\CertificationType',
'certification_type_id');
}
public function certification_course_topics_list()
{
return $this->hasMany('App\CertificationCourseTopicsList');
}
}
Child of Child Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class CertificationCourseTopicsList extends Model
{
protected $table = 'certification_topics_list';
public $timestamps = true;
use SoftDeletes;
protected $dates = ['deleted_at'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = array('certification_id', 'certification_topic_description');
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'created_at', 'updated_at',
];
public function certification_course_topics_list()
{
return $this->belongsToMany('App\Certification', 'certification_id');
}
}
The eloquent statement I am using is:
$CertificationTypes = App\CertificationType::orderBy('id',"asc")->with('certification_type')->get()->groupBy('id');
What I have accomplished is CertificationType has a child of Certifications attached in the query. What I need is the 2nd child to be in the query as well:
CertificationType::orderBy('id',"asc")->with('certification_type')->get()->groupBy('id')->with('certification')->get()->groupBy('id');
I also tried:
CertificationType::orderBy('id',"asc")->with('certification_type, certifications')->get()->groupBy('id');
That did not work: Call to undefined relationship [certification_type, certifications] on model [App\CertificationType].
Also tried:
CertificationType::orderBy('id',"asc")->with('certification_type', 'certifications')->get()->groupBy('id');
That did not work: Call to undefined relationship [certifications] on model [App\CertificationType].
Any help would be appreciated!
You need more order in code. I would make three models with proper relations as : belongsTo and hasMany. Then in each view you can use data from model with function of relation.
Example of proper model with relation:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany('App\Comment');
}
}
Read more here, that will save your time: https://laravel.com/docs/5.5/eloquent-relationships#one-to-many

laravel belongsTo on User Model not working

Following are my relations in laravel , I am unable to access company using User's Object, but i am getting null when i try to access it, please see my code below to get the picture
following are my models
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Session;
use Illuminate\Support\Facades\DB;
class User extends Authenticatable
{
use Notifiable;
use EntrustUserTrait;
protected $table = 'tbl_users';
protected $primaryKey = 'id';
protected $guarded = ['id'];
const API = 'api';
const WEB = 'web';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'last_login', 'Address', 'Age', 'DateOfBirth', 'created_by', 'deleted_by'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'is_admin' => 'boolean',
];
public function isAdmin()
{
return $this->is_admin;
}
static function GetUserNamebyID($id)
{
$name = User::select("name")->where(["id" => $id])->pluck('name');
if (isset($name[0])) {
return $name[0];
} else {
return '';
}
}
public function loginlogout()
{
$this->hasMany("App\Models\LoginLogoutLogs", 'userID');
}
public function company()
{
$this->hasMany("App\Models\Company", "company_id");
}
}
And following is my companies Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use DB;
use App\Models\CarePlanData;
use Session;
class Company extends Model
{
protected $table = 'companies';
protected $primaryKey = 'id';
protected $guarded = ['id'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'phone_no', 'address', 'password', 'description', 'city', 'company_logo', 'country', 'email'
];
static public function fetchAllActiveCompanies()
{
return DB::table("companies")->where(['is_active' => 1])->pluck('name', 'id');
}
// change company to hasmany
public function users()
{
return $this->hasmany('App\Models\User');
}
}
and this is how i am trying to access the Company , but i am getting null.
public function fetchCompany(){
$User = User::find($user->id);
dd($User->company());
}
First of all if a user belongs to 1 company then it should be:
public function company()
{
$this->belongsTo("App\Models\Company", "company_id");
}
then fetchCompany() should be
public function fetchCompany(){
$User = User::with('company')->find($user->id);
dd($User->company);
}
You need to use with to load the relations. You pass the name of the function which defines the relation in your User model to with like this with('function_name').
Your actual question is:
You have belongTo Relation between User and Company but when you trying to access the Company via user object, you get null
In your User.php Model put the following function but if you already have then leave it:
public function company()
{
$this->belongsTo("App\Models\Company", "company_id");
}
Then
Replace this function:
public function fetchCompany(){
$User = User::find($user->id);
dd($User->company());
}
To is one:
public function fetchCompany(){
$User = User::find($user->id);
if($User){
dd($User->company()->get());
}
}
or to this one:
public function fetchCompany(){
$User = User::find($user->id);
if($User){
dd($User->company);
}
}
actually if your company_id field is on user model, then your relation should be
public function company()
{
$this->belongsTo("App\Models\Company", "company_id");
}
unless a user can have many companies ?

How to access other related model data in Laravel?

I am creating a user profile page and I want to retrieve the data from my User model and UserProfile model. But I have a problem in getting the result. Here's what I did:
User model
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'username',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/*
public function isAdmin() {
return $this->admin;
}
*/
public function profile() {
return $this->hasOne('App\UserProfile');
}
}
UserProfile model
class UserProfile extends Model
{
protected $table = 'user_profile';
protected $fillable = [
'phone',
'address'
];
public function user() {
return $this->belongsTo('App\User');
}
}
Then I access the relation in my ProfileController
public function getProfile($username) {
$user = User::with('user_profile')->where('username', $username)->get();
dd($user);
}
And I got this error:
Call to undefined relationship [user_profile] on model [App\User].
The user_profile is my table name
Use proper relationship name:
$user = User::with('profile')->where('username', $username)->first();
Also, in this case you should use the first() method to get an user object.

Categories