$userid = Auth::user()->id;
$user= \App\User::findOrFail($userid);
$record = $user->company->timesheets()->where('id', $id)->first();
Aug 25, 2015
32
Level 51
Stuck with relationships. [HELP] :(
I have the following code in a controller:
/**
* Show Method
* GET/timesheets/{id}
*/
public function show($id)
{
$record = Auth::user()->company->timesheets()->where('id', $id)->first();
$now = new DateTime($record->weekCommencing);
$count = 0;
while($count < 7){
$dates[] = $now->format('Y-m-d');
$now->add(new DateInterval('P1D'));
$count++;
}
$placementData = $record->company->placements;
dd($placementData);
if($record->agency->placements->count() > 0){
$placements = array();
foreach($placementData as $key => $placement){
$placements[$placement->id] = $placement->name . ' (' . $placement->code . ')';
}
} else {
$placements = array(
'' => 'No Placements Available',
);
}
// Dates
$weeks = array();
$numberOfWeeks = 12;
$count = 0;
$now = new DateTime();
$date = new DateTime('last monday');
while($count < $numberOfWeeks){
// Calculate days remaining before these timesheets are deleted
$since = $now->format('U')-$date->format('U');
$deletion = ($numberOfWeeks*7)-floor($since/86400);
// Add the data to the $weeks array
$weeks[$date->getTimestamp()] = $date->format('d/m/Y');
// Move the date back seven days
$date->sub(new DateInterval('P7D'));
// Increase the counter
$count++;
}
// Store any amendments and pass them to the view
$amendments = false;
if($record->amendments){
$amendments = $record->amendments;
}
$canEdit = false;
if(Auth::user()->role == 'timesheet-manager') {
$canEdit = true;
}
return view('timesheet.form', compact('records', 'canEdit', 'placements', 'weeks', 'amendments', 'days'));
}
The corresponding models as follows:
// Company Model
<?php namespace Timesheet;
use Illuminate\Database\Eloquent\Model;
class Company extends Model {
protected $guarded = ['id'];
public $table = 'companies';
public $timestamps = false;
public function user()
{
return $this->hasMany('Timesheet\User');
}
public function timesheet()
{
return $this->hasMany('Timesheet\Timesheet');
}
public function placements()
{
return $this->hasMany('Timesheet\Placement');
}
/**
* Timesheets
*/
public function timesheets() {
return $this->hasMany('Timesheet\Timesheet', 'company_id', 'id');
}
}
// Timesheet Model
<?php namespace Timesheet;
use DateTime;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Timesheet extends Model {
use SoftDeletes;
protected $guarded = ['id'];
public $table = 'timesheets';
/**
* Dates to be treated as Carbon instances
*
* @var array
*/
public $dates = [
'created_at',
'deleted_at',
'weekCommencing'
];
/**
* Return the 'created_at' date in the specified format
*/
public function getDate($format = 'd/m/Y') {
$date = new DateTime($this->created_at);
return $date->format($format);
}
/**
* Company Relationship
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function company()
{
return $this->belongsTo('Timesheet\Company');
}
public function agency()
{
return $this->belongsTo('Timesheet\Company');
}
/**
* User Relationship
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function user()
{
return $this->belongsTo('Timesheet\User');
}
public function placement()
{
return $this->belongsTo('Timesheet\Placement', 'agency_id');
}
/**
* Timesheet Days
*/
public function days()
{
return $this->hasMany('Timesheet\TimesheetDay')
->orderBy('date', 'ASC');
}
/**
* Approved User
*/
public function userApproved()
{
return $this->belongsTo('Timesheet\User', 'user_approved_id');
}
}
// User Model
<?php namespace Timesheet;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword, SoftDeletes;
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $guarded = ['id'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
public function agency()
{
return $this->belongsTo('Timesheet\Company', 'agency_id');
}
public function placement()
{
return $this->belongsTo('Timesheet\Placement');
}
public function company()
{
return $this->belongsTo('Timesheet\Company', 'agency_id');
}
public function timesheet()
{
return $this->hasMany('Timesheet\Timesheet');
}
public function timesheetDays()
{
return $this->hasMany('Timesheet\TimesheetDay');
}
/**
* Submitted Timesheets by User
*/
public function submittedTimesheets() {
return $this->hasMany('Timesheet\Timesheet');
}
/**
* Return the User's full name
*/
public function fullName()
{
return $this->first_name . ' ' . $this->last_name;
}
/**
* Returns a trashed model by the given field and value
*
* @param string $field Field
* @param string $value Value
* @return Resource
*/
static public function getTrashedBy($field, $value)
{
$users = User::onlyTrashed()->where($field, $value);
if ($users->count() == 0) return false;
if ($users->count() == 1) {
return $users->first();
}
return $users->get();
}
}
// TimesheetDay Model
<?php
namespace Timesheet;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class TimesheetDay extends Model
{
use SoftDeletes;
protected $dates = [
'deleted_at',
];
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'timesheets_days';
/**
* Guarded attributes (all other attributes are implied fillable)
*/
protected $guarded = array('id');
public function user()
{
return $this->belongsTo('Timesheet\User');
}
public function placement()
{
return $this->hasMany('Timesheet\Placement');
}
/**
* Timesheet
*/
public function timesheet() {
return $this->belongsTo('Timesheet\Timesheet');
}
/**
* Returns a model by the given field and value
*
* @param string $field Field
* @param string $value Value
* @return Resource
*/
static public function getBy($field, $value) {
$timesheetDays = TimesheetDay::where($field, $value);
if ($timesheetDays->count() == 0) return false;
if ($timesheetDays->count() == 1) {
return $timesheetDays->first();
}
return $timesheetDays->get();
}
/**
* Returns a trashed model by the given field and value
*
* @param string $field Field
* @param string $value Value
* @return Resource
*/
static public function getTrashedBy($field, $value) {
$timesheetDays = TimesheetDay::onlyTrashed()->where($field, $value);
if ($timesheetDays->count() == 0) return false;
if ($timesheetDays->count() == 1) {
return $timesheetDays->first();
}
return $timesheetDays->get();
}
}
The html is as follows:
@extends('app')
@section('title')
Submitted Timesheet
@endsection
@section('content')
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<?php
if($canEdit){
$formArray = array(
'url' => secure_url('timesheets/' . $record->id),
'method' => 'put',
'class' => 'form-horizontal',
);
} else {
$formArray = array(
'class' => 'form-horizontal',
);
}
echo Form::model($record, $formArray);
$payableMileageTotal = 0;
$totalPayableHoursTotal = array(
'hours' => 0,
'minutes' => 0,
);
$totalDay = 0;
?>
<div class="row">
<div class="col-md-12">
<!-- Staff Member -->
<label class="col-sm-2 control-label">Staff Member</label>
<div class="col-sm-2">
<?php
// New timesheets since October 2014 use user_id relation
// Old timesheets used a manual string insertion for the staff name
if (is_object($record->user())) {
echo '<input type="text" name="staffMember" class="form-control" value="' .$record->user->fullName().'" disabled>';
} else {
echo '<input type="text" name="staffMember" class="form-control" value="' .$record->staffMember .'" disabled>';
}
?>
</div>
<!-- Placement Name -->
<label class="col-sm-2 control-label"><?php echo Lang::get('staff-timesheets.form.table.placement'); ?></label>
<div class="col-sm-2"><input type="text" name="placementName" class="form-control" value="<?php echo $record->placement->name.' ('.$record->placement->code.')'; ?>" disabled></div>
<!-- Placement Manager -->
<label class="col-sm-2 control-label"><?php echo Lang::get('frontend.timesheet.table.manager'); ?></label>
<div class="col-sm-2"><input type="text" name="placementManager" class="form-control" value="<?php echo $record->placementLineManager; ?>" disabled></div>
<!-- Week Commencing -->
<label class="col-sm-2 control-label"><?php echo Lang::get('staff-timesheets.form.table.week'); ?></label>
<div class="col-sm-2">
<?php
$timestamp = new DateTime($record->weekCommencing);
echo Form::select('weekCommencing', $weeks, $timestamp->getTimestamp(), array(
'class' => 'form-control',
'required' => 'required',
'disabled' => ($canEdit ? null : 'disabled'),
));
?>
</div>
<hr />
<table class="table table-striped">
<thead>
<tr>
<th><?php echo Lang::get('staff-timesheets.form.table.day'); ?></th>
<th><?php echo Lang::get('staff-timesheets.form.table.startTime'); ?></th>
<th>Breaks</th>
<th><?php echo Lang::get('staff-timesheets.form.table.endTime'); ?></th>
<th><?php echo Lang::get('staff-timesheets.form.table.payableMileage'); ?></th>
<th><?php echo Lang::get('staff-timesheets.form.table.totalPayableHours'); ?></th>
<th><?php echo Lang::get('staff-timesheets.form.table.comments'); ?></th>
<th>Total Day Shift (Decmial)</th>
</tr>
</thead>
<tbody>
<?php
foreach($record->days as $key => $day){
$dayDateTime = new DateTime($day->date);
$arrayDay = strtolower($dayDateTime->format('l'));
?>
<tr>
<td>
<label class="control-label">
<?php
echo $dayDateTime->format('l');
?>
</label>
</td>
<td>
<?php
echo Form::text($arrayDay . '[startTime]', $day->startTime, array(
'class' => 'form-control timepicker',
'autocomplete' => 'off'
));
if($amendments && isset($amendments[$arrayDay]['startTime'])){
?>
<?php echo Lang::get('timesheets.form.table.amendment', array('amendment' => $amendments[$arrayDay]['startTime'])); ?>
<?php
}
?>
</td>
<td>
<?php
echo Form::text($arrayDay . '[breaks]', $day->breaks, array(
'class' => 'form-control',
'autocomplete' => 'off'
));
if($amendments && isset($amendments[$arrayDay]['breaks'])){
?>
<?php echo Lang::get('timesheets.form.table.amendment', array('amendment' => $amendments[$arrayDay]['endTime'])); ?>
<?php
}
?>
</td>
<td>
<?php
echo Form::text($arrayDay . '[endTime]', $day->endTime, array(
'class' => 'form-control timepicker',
'autocomplete' => 'off',
));
if($amendments && isset($amendments[$arrayDay]['endTime'])){
?>
<?php echo Lang::get('timesheets.form.table.amendment', array('amendment' => $amendments[$arrayDay]['endTime'])); ?>
<?php
}
?>
</td>
<td>
<?php
echo Form::input('number', $arrayDay . '[payableMileage]', $day->payableMileage, array(
'class' => 'form-control',
'data-attribute' => 'payableMileage',
'min' => '0'
));
if($amendments && isset($amendments[$arrayDay]['payableMileage'])){
?>
<?php echo Lang::get('timesheets.form.table.amendment', array('amendment' => $amendments[$arrayDay]['payableMileage'])); ?>
<?php
}
$payableMileageTotal += $day->payableMileage;
?>
</td>
<td>
<?php
$hours = 0;
$start = $day->startTime;
$finish = $day->endTime;
$dayBreak = $day->breaks;
$startArray = explode(':', $start);
$startTime = \Carbon\Carbon::createFromTime($startArray[0], $startArray[1], $startArray[2]);
$endArray = explode(':', $finish);
$endTime = \Carbon\Carbon::createFromTime($endArray[0], $endArray[1], $endArray[2]);
$breakArray = explode(':', $dayBreak);
$breakTime = \Carbon\Carbon::createFromTime($breakArray[0], $breakArray[1], $breakArray[2]);
if (isset($breakTime->hour))
{
$breakTimeMinutes = floor($breakTime->hour);
}
if ($breakTime->minute) {
$breakTimeMinutes = floor($breakTime->minute);
}
//$breakTimeMinutes = $breakTime->minute;
$minutesWithBreak = $startTime->diffInMinutes($endTime->subMinutes($breakTimeMinutes));
$hours = $minutesWithBreak / 60;
echo Form::text($arrayDay . '[totalPayableHours]', $hours, array(
'class' => 'form-control timepicker',
'data-attribute' => 'totalPayableHours',
'autocomplete' => 'off',
'disabled' => ($canEdit ? null : 'disabled'),
));
?>
</td>
<td>
<?php
echo Form::text($arrayDay . '[comments]', $day->comments, array(
'class' => 'form-control',
'disabled' => ($canEdit ? null : 'disabled'),
));
if($amendments && isset($amendments[$arrayDay]['comments'])){
?>
<?php echo Lang::get('timesheets.form.table.amendment', array('amendment' => $amendments[$arrayDay]['comments'])); ?>
<?php
}
?>
</td>
<td>
<?php
$b = $hours;
$c = preg_replace("/([0-9]+)\./", "\\1", $b);
// echo $c;
?>
</td>
</tr>
<?php } ?>
<tr class="totals">
<td class="text-right" colspan="3">
<h3><?php echo Lang::get('staff-timesheets.form.table.totals'); ?></h3>
</td>
<td></td>
<td>
<h3 id="payableMileageTotal"><?php echo $payableMileageTotal; ?></h3>
</td>
<td colspan="2">
<h3 id="totalPayableHoursTotal"><?php echo $hours * 7 .' hours'; ?></h3>
</td>
</tr>
</tbody>
</table>
<div class="form-group">
<div class="col-lg-3">
</div>
</div>
{!! Form::close() !!}
</div>
</div><!-- /row -->
</div>
</div>
@endsection
But I keep getting Call to a member function timesheets() on null error and just banging my head against a brick wall here, can't seem to figure it out why this happening.
My data in the DB is all correct and tallies up with each other, but still not no avail.
Please or to participate in this conversation.



thanks for helping so far do appreciate it :)