Laravel one to many relationship doesn't work anymore - php

This relationship of mine was working last week, but it stopped working.
When i use it in my blade template it says: Trying to get property 'name' of non-object.
The weird thing is, when i use it in dd() it perfectly shows, but when i try to print it in blade, it doesn't.
Code PaymentsController
<?php
namespace App\Http\Controllers;
use App\Betaling;
use App\Settings;
use Illuminate\Http\Request;
class PaymentsController extends Controller
{
public function index(){
$user_id = auth()->user('id');
$role = auth()->user()->role_id;
$settings = Settings::where('user_id', $user_id->id)->first();
if ($role === 1){
$totaalaantalbetalingen = Betaling::all();
} else {
$totaalaantalbetalingen = Betaling::where('user_id', $user_id->id)->get();
}
return view('payments.index', compact(['totaalaantalbetalingen','role', 'user_id', 'settings']));
}
}
Code index.blade.php
#foreach($totaalaantalbetalingen as $betaling)
<tr>
<th scope="row">{{ $betaling->id }}</th>
#if($role === 1)
<td>{{ $betaling->user->name }} </td>
#endif
<td>{{ $betaling->customer->name }}</td>
<td>{{ $betaling->reference}}</td>
<td>€ {{ $betaling->amount}}</td>
<td>{{ $betaling->time_of_invoice }}</td>
<td>{{ $betaling->time_of_payment }}</td>
<td></td>
<td>{{ $betaling->user->location }}</td>
</tr>
#endforeach
code User model:
public function betalingen(){
return $this->hasMany(Betaling::class);
}
code Betaling model:
public function customer(){
return $this->belongsTo(User::class);
}
public function user(){
return $this->belongsTo(User::class);
}
code Customer model:
public function betaling(){
return $this->hasMany(Betaling::class);
}

pass auth()->user()->id and in blade file check !empty($totaalaantalbetalingen)
code User model:
public function betalingen(){
return $this->hasMany('App\Betaling','betalingenid','id'); // pass foreign key for ex.
}
code Betaling model:
public function customer(){
return $this->belongsTo('App\User','customer_id','id');// pass foreign key for ex.
}
public function user(){
return $this->belongsTo('App\User','user_id','id');// pass foreign key for ex.
}
code Customer model:
public function betaling(){
return $this->hasMany('App\Betaling','customer_id','id');// pass foreign key for ex.
}
Controller
public function index(){
$user_id = auth()->user()->id;
$role = auth()->user()->role_id;
$settings = Settings::where('user_id', $user_id)->first();
if ($role == 1){
$totaalaantalbetalingen = Betaling::all();
} else {
$totaalaantalbetalingen = Betaling::where('user_id', $user_id)->get();
}
return view('payments.index', compact(['totaalaantalbetalingen','role', 'user_id', 'settings']));
}
blade.php
#if(!empty($totaalaantalbetalingen) && isset($totaalaantalbetalingen))
#foreach($totaalaantalbetalingen as $betaling)
<tr>
<th scope="row">{{ $betaling->id ?? '' }}</th>
#if($role === 1)
<td> {{ $betaling->user->name ?? '' }} </td>
#endif
<td> {{ $betaling->customer->name ?? '' }} </td>
<td> {{ $betaling->reference ?? '' }} </td>
<td> € {{ $betaling->amount ?? '' }} </td>
<td> {{ $betaling->time_of_invoice ?? '' }} </td>
<td> {{ $betaling->time_of_payment ?? '' }} </td>
<td> </td>
<td> {{ $betaling->user->location ?? '' }} </td>
</tr>
#endforeach
#endif

Related

Undefined variable: blogcat (View: /home/techpriest/joseph/resources/views/admin/view_category.blade.php)

Undefined variable: blogcat (View: /home/techpriest/joseph/resources/views/admin/view_category.blade.php) this is my error message in laravel 8 but when I look at my code all seems well.
here is my code.
AdminController
public function addBlogCat (Request $request){
if ($request->isMethod('post')) {
$data = $request->all();
$blogcat = new Foliocategories;
$blogcat->name = $data['category_name'];
$blogcat->save();
return redirect ('/blog/categories');
}
return view ('admin.view_category');
}
public function viewBlogCat (){
$blogcat = DB::select('select * from foliocategories');
return view ('admin.view_category', ['blogcat'=>$blogcat]);
}
And here is my view;
#foreach($blogcat as $blogcat)
<tr>
<td>{{ $blogcat->id }}</td>
<td>{{ $blogcat->name }}</td>
<td>{{ $blogcat->created_at }}</td>
<td><span class="badge badge-danger">Due</span></td>
<td class="action h4">
<div class="table-action-buttons">
<a class="edit button button-box button-xs button-info" href="#"><i class="zmdi zmdi-edit"></i></a>
<a class="delete button button-box button-xs button-danger" href="#"><i class="zmdi zmdi-delete"></i></a>
</div>
</td>
</tr>
#endforeach
I found two issues here. In the addBlogCat action, you don't inject any blog category. The viewBlogCat is not bad, but in the view, you are using a loop with a model instance.
What about rewrite the code to this, lets use full meaningful variable names:
public function addBlogCategory(Request $request)
{
if ($request->isMethod('post')) {
$data = $request->all();
Foliocategories::create(['name' => $request->input('category_name')]);
return redirect ('/blog/categories');
}
return view ('admin.view_category', [
'blogCatogories' => Foliocategories::all();
]);
}
public function viewBlogCategories()
{
$blogCategories = Foliocategories::all();
return view ('admin.view_category', compact('blogCategories'));
}
Then in the view:
#foreach($blogCategories as $blogCategory)
<tr>
<td>{{ $blogCategory->id }}</td>
<td>{{ $blogCategory->name }}</td>
<td>{{ $blogCategory->created_at }}</td>
</tr>
#endforeach

Laravel relations are not working?

I have relation with Deposit model but relations are not working.
error:Trying to get property of non-object (View: C:\xamp\htdocs\assets\core\resources\views\user\deposit-history.blade.php)
View code
<tbody>
#php $i = 0;#endphp
#foreach($deposit as $p)
#php $i++;#endphp
<tr>
<td>{{ $i }}</td>
<td width="10%">{{ date('d-F-Y h:s:i A',strtotime($p->created_at)) }}</td>
<td><span class="aaaa"><strong>{{ $p->plan->name }}</strong></span></td>
<td>#{{ $p->deposit_number }}</td>
<td>{{ $p->amount }} - {{ $basic->currency }}</td>
<td width="13%">{{ $p->percent }} %</td>
<td>{{ $p->time }} - times</td>
<td><span class="aaaa"><strong>{{ $p->compound->name }}</strong></span></td>
<td>
#if($p->status == 0)
<span class="label label-secondary"><i class="fa fa-spinner"></i> Running</span>
#else
<span class="label label-success"><i class="fa fa-check" aria-hidden="true"></i> Completed</span>
#endif
</td>
</tr>
#endforeach
</tbody>
Model code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Deposit extends Model
{
protected $table = 'deposits';
protected $fillable = ['deposit_number','user_id','plan_id','amount','status','percent','time','compound_id'];
public function plan()
{
return $this->belongsTo(Plan::class,'plan_id');
}
public function compound()
{
return $this->belongsTo(Compound::class,'compound_id');
}
public function user()
{
return $this->belongsTo(User::class,'user_id');
}
}
In your view you have:
<td><span class="aaaa"><strong>{{ $p->plan->name }}</strong></span></td>
And this:
<td><span class="aaaa"><strong>{{ $p->compound->name }}</strong></span></td>
If two line will work if you always have $p->plan and $p->compound. But if you don't have(e.g. null) $p->plan or $p->compound it will throw an exception(Trying to get property of non-object).
So, when will these property be null?
Firstly, you need to make sure that you have plan_id and compound_id in your deposits table. Otherwise, the relational property will return null.
Secondly, It can be null if the plan_id or compound_id is empty/null or a value that doesn't exist in plans or compounds table.
What is the solution even if it's null?
If you need to show other field even if your plan or compound is null then you can change the above to line into the following lines:
<td><span class="aaaa"><strong>{{ isset($p->plan) ? $p->plan->name : '' }}</strong></span></td>
and
<td><span class="aaaa"><strong>{{ isset($p->compound) ? $p->compound->name : '' }}</strong></span></td>

Laravel: Eloquent returning an object I can't iterate over

I have a mySQL DB schema like this:
table RECIPES:
int id, PK;
int salesman_id;
int doctor_id;
date order_date;
int status;
table RECIPE_STATUS:
int id, PK;
int recipe_status_code;
varchar recipe_status_name;
In Laravel I have the following php classes:
AdminRecipesController.php
namespace RatCMS\Controllers;
use App\Http\Controllers\Controller;
use Auth;
use RatCMS\Models\Recipes;
use RatCMS\Models\RecipeStatus;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class AdminRecipesController extends Controller
{
public function index()
{
$recipes = Recipes::with('recipeStatus')->get();
return view('admin.recipes.news', compact('recipes'));
}
}
Recipes.php
<?php
namespace RatCMS\Models;
use Illuminate\Database\Eloquent\Model;
class Recipes extends Model
{
protected $table = 'RECIPES';
protected $fillable = ['salesman_id', 'doctor_id', 'order_date', 'status'];
public function recipeStatus() {
return $this->hasOne(\RatCMS\Models\RecipeStatus::class, 'recipe_status_code', 'status');
}
}
RecipeStatus.php
<?php
namespace RatCMS\Models;
use Illuminate\Database\Eloquent\Model;
class RecipeStatus extends Model
{
protected $table = 'RECIPE_STATUS';
protected $fillable = [];
public function recipes() {
return $this->belongsTo(\RatCMS\Models\Recipes::class);
}
}
blade view
<div class="box-body">
#include('admin.partials.session_success')
#if($recipes->isEmpty())
<p class="text-center">No recipes available.</p>
#else
<table class="table table-bordered">
<tr>
<th style="width: 10px">#</th>
<th>Salesman</th>
<th>Doctor</th>
<th>Date</th>
<th>Status</th>
<th style="width:100px">Actions</th>
</tr>
#foreach($recipes as $recipe)
{{ $recipe }}
<tr>
<td>{{ $recipe->id }}</td>
<td>{{ $recipe->salesman_id }}</td>
<td>{{ $recipe->doctor_id }}</td>
<td>{{ $recipe->order_date }}</td>
<td>{{ $recipe->recipe_status->recipe_status_name }}</td>
<td>
<form style="display: inline-block" action="{{ url('admin/recipes/' . $recipe->id) }}" method="POST">
{{ csrf_field() }}
<input name="_method" type="hidden" value="DELETE">
<button type="submit" class="btn btn-danger"><i class="fa fa-close" aria-hidden="true"></i> Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
#endif
</div>
When I do {{ $recipe }} in the view, I get the following result:
{"id":1,"salesman_id":"4","doctor_id":"3","order_date":null,"status":"0","recipe_status":{"id":1,"recipe_status_code":"0","recipe_status_name":"Not Recieved"}}
so there is some data being return by Eloquent regarding the recipe status (Not Recieved text), but when I do {{ $recipe->recipe_status }} it fails every time. Even $recipes['recipe_status'] is no help.
Could someone help? Thanks
Relationship should be belongsTo():
public function recipeStatus() {
return $this->belongsTo(\RatCMS\Models\RecipeStatus::class, 'status', 'recipe_status_code');
}
With correct relationship your code will add relationship data to collection, so you'll be able to get status:
$recipe->recipeStatus->recipe_status_name

Laravel 5 Undefined property: Illuminate\Database\Eloquent\Collection::$basicdetails

what is my mistake?
my controller :
public function index()
{
$employees = Employee::all();
return view('employee.view_all_employee_details', compact('employees'));
}
My Employee Model function :
public function basicdetails()
{
return $this->hasOne('App/EmployeeAdditionalDetail' , 'emp_id' , 'emp_id');
}
My EmployeeAdditionalDetail model :
public function employeeDetails()
{
return $this->belongsTo('App\Employee' , 'emp_id' , 'emp_id');
}
My View
#if(count($employees) > 0)
#foreach($employees as $employee)
<tr>
<td> {{ $employee->first_name }} </td>
<td> {{ $employee->manager_id }} </td>
<td>
{{ $employee->basicdetails->personal_email }} </p> **Error showing here**
</td>
</tr>
#endforeach
#else
{!! "<tr><td>No Recod Found</td></tr>" !!}
#endif
My Error:
ErrorException in
C:\xampp\htdocs\socialhub\app\Http\Controllers\EmployeeController.php
line 22: Undefined property:
Illuminate\Database\Eloquent\Collection::$basicdetails
I suspect the issue is with the third parameter of $this->hasOne(..), it should be 'local_key', normally this would be 'id'.
Try removing the third parameter, or put the correct local_key:
public function basicdetails()
{
return $this->hasOne('App/EmployeeAdditionalDetail' , 'emp_id');
}

Passing input (form) from a page to itself

I am working on my first laravel script, trying to submit a form and see the input on the same page. I am working on this problem for days, hopefully someone can solve this. The problem is that i get this error:
Undefined variable: data (View: D:\Programmer\wamp\www\laravel\app\views\bassengweb.blade.php)
view: Bassengweb.blade.index
#extends('master')
#section('container')
<h1>BassengWeb testrun</h1>
<table>
{{ Form::open(array('route' => 'bassengweb', 'url' => '/', 'method' => 'post')) }}
<tr>
<td>{{ Form::label('bassengId', 'Basseng ID')}}</td>
<td>{{ Form::text('bassengId') }}</td>
</tr>
<tr>
<td>{{ Form::label('frittKlor', 'Fritt Klor')}}</td>
<td>{{ Form::text('frittKlor') }}</td>
</tr>
<tr>
<td>{{ Form::label('bundetKlor', 'Bundet Klor')}}</td>
<td>{{ Form::text('bundetKlor') }}</td>
</tr>
<tr>
<td>{{ Form::label('totalKlor', 'Total Klor')}}</td>
<td>{{ Form::text('totalKlor') }}</td>
</tr>
<tr>
<td>{{ Form::label('ph', 'PH')}}</td>
<td>{{ Form::text('ph') }}</td>
</tr>
<tr>
<td>{{ Form::label('autoPh', 'Auto PH')}}</td>
<td>{{ Form::text('autoPh') }}</td>
</tr>
<tr>
<td>{{ Form::submit('Lagre målinger') }}</td>
{{ Form::close() }}
</table>
#if($data)
{{ $data->bassengId }}
#endif
#stop
Homecontroller.php
<?php
class HomeController extends BaseController {
public function showWelcome()
{
return View::make('hello');
}
public function showTest()
{
return View::make('test');
}
public function getInput()
{
$input = Input::all();
print_r($input); die();
return View::make('bassengweb')->with('data', '$input');
}
}
view: master.blade.php
<div class="container">
#yield('container')
</div>
routes.php
Route::get('/', function()
{
return View::make('bassengweb');
});
//Route::post('/', array('uses'=>'HomeController#getInput'));
Route::post('/',function(){
$input = Input::all();
//for inspecting input
print_r($input);
die();
//to send input to view but before sending to view comment last two lines
return View::make('bassengweb')->with('data',$input);
You enclosed $input in single quotes in your HomeController.php, instead try:
<?php
class HomeController extends BaseController {
public function showWelcome()
{
return View::make('hello');
}
public function showTest()
{
return View::make('test');
}
public function getInput()
{
$input = Input::all();
print_r($input); die();
return View::make('bassengweb')->with('data', $input);
}
}
In your routes.php, change route registration a little.
Route::get('/', function()
{
$data = Input::all();
return View::make('bassengweb', compact('data'));
});

Categories