Attempt to read property "nama" on int - php

im trying to get the latest data on database, im using this on my views :
#foreach ($shows as $s)
<tbody>
<tr>
<th scope="row">{{$loop->iteration}}</th>
<td>{{$s->nama}}</td>
<td>{{$s->umur}}</td>
<td>{{$s->alamat}}</td>
<td>{{$s->nama_ortu}}</td>
<td>{{$s->posyandu}}</td>
<td>{{$s->result}}</td>
</tr>
</tbody>
#endforeach
and on controller :
public function showresultpasien()
{
$shows = DB::table('pasiens')->orderBy('id', 'DESC')->first();
return view('result', compact('shows'));
}
did i doin something wrong ?

The name of the function in the model cannot be the same as the name of a field in your table. Also in my case the column names do not follow the laravel/eloquent nomenclature so another parameter is added to belongsTo with the field name

Related

how can i change the value inside collection laravel?

i tried so hard to change the value inside collection and nothings was happen
here is my footage of datatable in html
i want to change that value of 0 and 1 into 'active' and 'non-active'
i tried change it on my function controller and didn't work
controller.php
public function reportView()
{
$data = ReportViewAll::paginate(5);
$reportviewall = $data->map(function($item, $key){
$key = 'crewprogram_isdisabled';
($item = 0) ? $item = 'active' : $item = 'non-active';
return $item;
});
return view('CrewProgram.ReportView.index', compact('reportviewall'));
}
how do i solve that?
and instead change it in function, can i change it in Eloquent model?
Eloquent Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ReportViewAll extends Model
{
protected $connection = 'sqlsrv2';
protected $table ='view_mastercrewprogram';
}
How can i solve this?
EDIT
this is my table, i tried some stuff up in my blade and still not working
table.blade.php
<tbody>
#foreach($reportviewall as $mastercrew)
<tr>
<td class="nik">{{$mastercrew->employee_nik}}</td>
<td class="nik">{{$mastercrew->employee_nama}}</td>
<td class="nik">{{$mastercrew->crewprogramposition_name}}</td>
<td class="nik">{{$mastercrew->show_focus_id}}</td>
<td class="nik">{{$mastercrew->show_name}}</td>
<td class="nik">{{$mastercrew->crewprogrammemo_placement_id}}</td>
<td class="nik">{{ \Carbon\Carbon::parse($mastercrew->crewprogrammemo_placement_date)->format(' d-m-Y ')}}</td>
<td class="nik">{{
($mastercrew->crewprogram_isdisabled = '0') ? $mastercrew->crewprogram_isdisabled = 'active' : $mastercrew->crewprogram_isdisabled = 'non-active'
}}</td>
<td class="nik">{{$mastercrew->crewprogrammemo_dismissal_id}}</td>
<td class="nik">{{ \Carbon\Carbon::parse($mastercrew->crewprogrammemo_dismissal_date)->format(' d-m-Y ')}}</td>
</tr>
#endforeach
</tbody>
So I know you have solved your issue in your code by swapping the = for a correct comparison == so that you show active/non-active as asked. However, I would like to show you a few different ways of acheiving the same outcome but with better readability.
Option 1: Zero is falsey
I assume your table.blade.php field now looks like this:
<td class="nik">{{
($mastercrew->crewprogram_isdisabled == '0') ? $mastercrew->crewprogram_isdisabled = 'active' : $mastercrew->crewprogram_isdisabled = 'non-active'
}}</td>
This can be refactored to the below and you should get the same result.
<td class="nik">{{$mastercrew->crewprogram_isdisabled ? 'non-active' : 'active'}}</td>
Just as a reference the correct word is inactive when something is not active.
Option 2: Add a mutator method to your model
Laravel has lots of additional features you can do on your models to help when using them in your blade views. One of these is called mutators (see docs: https://laravel.com/docs/7.x/eloquent-mutators#introduction).
This basically lets you add additional fields to your models to prevent adding unnecessary logic to your blade views. I recommend doing this if you plan to display active/non-active in other places as well.
So you could add this function to your ReporyViewAll model:
public function getActiveStatusAttribute()
{
return $this->crewprogram_isdisabled ? 'non-active' : 'active';
}
Then in your table.blade.php you can change the field to this:
<td class="nik">{{$mastercrew->active_status}}</td>
to solve the problem its just use '==' instead '=', maybe i need to sleep

Creating function for laravel controller/view to load database values

I'm working on updating a laravel blade template to insert some database info into an html table. IN order to do this, I'm having to add new data to the controller for this blade and that's where I'm having some troubles.
I'm still trying to understand more with laravel, so I'm thinking my syntax or methods of creating this data are incorrect but I just can't put my finger on it right now.
In my function below, the $calls_allowed portion was already existing and it works on the page currently. I created the $contact_events portion of the function and that's where my problem is.
IN my view, I created a foreach loop and if statement around the html table in question. The table loads, but it's empty even though there are records in the database for the dealer.
I'm trying to say
if $dealer-> id matches contact_events.dealer_num, load all records for that dealer
contact_events is the table and dealer_num is the column I'm matching, then I'm trying to load the columns from that table (updated_at,method,notes) into the html table.
The affected code is below. The view/route/controller work, it's just this function I'm creating that isn't loading data. Any help is much appreciated.
Controller code:
public function show($id)
{
$d = Dealer::find($id);
if(!$d){
\Session::flash('warning_message', 'Sorry that resource can not be found.');
return redirect()->route('account.dealer.index');
}
$calls_allowed = DB::table('dealers.dealers')->
where('dealer_num', $id)->
pluck('calls_allowed');
$contact_events = DB::table('dealers.contact_events')->
where('dealer_num', $id)->
pluck('updated_at', 'method', 'notes');
if(!empty($calls_allowed)){
$d->calls_allowed = $calls_allowed[0];
} else {
$d->calls_allowed = null;
}
return view('Account.Dealer.show')->with('dealer', $d);
}
View code:
<thead>
<tr>
<th>Contacted Date</th>
<th>Type of Contact</th>
<th>Call Notes</th>
</tr>
</thead>
#foreach($dealer->contact_events as $events)
#if($events->dealer_num = $dealer->id)
<tbody>
<tr>
<td>{{$events->updated_at}}</td>
<td>{{$events->method}}</td>
<td>{{$events->notes}}</td>
</tr>
</tbody>
#endif
#endForeach
It looks like you are not assigning the data to the object after retrieving from database.
$contact_events = DB::table('dealers.contact_events')->
where('dealer_num', $id)->
pluck('updated_at', 'method', 'notes');
// add this
$d->contact_events = $contact_events;
This seems like a perfect time to use the power of Laravel's Eloquent ORM...
Check out the with and has in the Laravel docs
This will require some finessing based on your needs, but it will be something like this:
$d = Dealer::where('id', '=', $id)
->with('contact_events')->first();
This uses Eloquent to get all of the contact_events that belong to the dealer with the $id.
Then you can do something like this
note: this assumes that calls_allowed is a record on the dealer table. if I misunderstood that, you can still run than you can include that just as you have it.
#if(!is_null($dealer->calls_allowed)
#foreach($dealer->contact_events as $events)
<tbody>
<tr>
<td>{{$events->updated_at}}</td>
<td>{{$events->method}}</td>
<td>{{$events->notes}}</td>
</tr>
</tbody>
#endForeach
#endif

Trying to get property of non-object - Laravel 5

I'm trying to echo out the name of the user in my article and I'm getting the
ErrorException: Trying to get property of non-object
My code:
Models
1. News
class News extends Model
{
public function postedBy()
{
return $this->belongsTo('App\User');
}
protected $table = 'news';
protected $fillable = ['newsContent', 'newsTitle', 'postedBy'];
}
2. User
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
}
Schema
table users
table news
Controller
public function showArticle($slug)
{
$article = News::where('slug', $slug)->firstOrFail();
return view('article', compact('article'));
}
Blade
{{ $article->postedBy->name }}
When I try to remove the name in the blade {{ $article->postedBy }} it outputs the id, but when I try to add the ->name there it says Trying to get property of non-object but I have a field namein my table and aUser` model. Am I missing something?
Is your query returning array or object? If you dump it out, you might find that it's an array and all you need is an array access ([]) instead of an object access (->).
I got it working by using Jimmy Zoto's answer and adding a second parameter to my belongsTo. Here it is:
First, as suggested by Jimmy Zoto, my code in blade
from
$article->poster->name
to
$article->poster['name']
Next is to add a second parameter in my belongsTo,
from
return $this->belongsTo('App\User');
to
return $this->belongsTo('App\User', 'user_id');
in which user_id is my foreign key in the news table.
If you working with or loops (for, foreach, etc.) or relationships (one to many, many to many, etc.), this may mean that one of the queries is returning a null variable or a null relationship member.
For example: In a table, you may want to list users with their roles.
<table>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
#foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->role->name }}</td>
</tr>
#endforeach
</table>
In the above case, you may receive this error if there is even one User who does not have a Role. You should replace {{ $user->role->name }} with {{ !empty($user->role) ? $user->role->name:'' }}, like this:
<table>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
#foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ !empty($user->role) ? $user->role->name:'' }}</td>
</tr>
#endforeach
</table>
Edit:
You can use Laravel's the optional method to avoid errors (more information). For example:
<table>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
#foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ optional($user->role)->name }}</td>
</tr>
#endforeach
</table>
If you are using PHP 8, you can use the null safe operator:
<table>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
#foreach ($users as $user)
<tr>
<td>{{ $user?->name }}</td>
<td>{{ $user?->role?->name }}</td>
</tr>
#endforeach
</table>
I implemented a hasOne relation in my parent class, defined both the foreign and local key, it returned an object but the columns of the child must be accessed as an array.
i.e. $parent->child['column']
Kind of confusing.
REASON WHY THIS HAPPENS (EXPLANATION)
suppose we have 2 tables users and subscription.
1 user has 1 subscription
IN USER MODEL, we have
public function subscription()
{
return $this->hasOne('App\Subscription','user_id');
}
we can access subscription details as follows
$users = User:all();
foreach($users as $user){
echo $user->subscription;
}
if any of the user does not have a subscription, which can be a case.
we cannot use arrow function further after subscription like below
$user->subscription->abc [this will not work]
$user->subscription['abc'] [this will work]
but if the user has a subscription
$user->subscription->abc [this will work]
NOTE: try putting a if condition like this
if($user->subscription){
return $user->subscription->abc;
}
It happen that after some time we need to run
'php artisan passport:install --force
again to generate a key this solved my problem ,
I had also this problem. Add code like below in the related controller (e.g. UserController)
$users = User::all();
return view('mytemplate.home.homeContent')->with('users',$users);
Laravel optional() Helper is comes to solve this problem.
Try this helper so that if any key have not value then it not return error
foreach ($sample_arr as $key => $value) {
$sample_data[] = array(
'client_phone' =>optional($users)->phone
);
}
print_r($sample_data);
Worked for me:
{{ !empty($user->role) ? $user->role->name:'' }}
In my case the problem was in wrong column's naming:
In model Product I've tried to access category relationship instance to get it's name, but both column name and relationship had the same name:
category
instead of:
category_id - for column name
category - for relationship
Setting up key name in relationship definition like
public function category():hasOne
{
return $this->hasOne(Category::class,'category');
}
didn't help because as soon as Laravel found property named category gave up on looking for relationship etc.
Solution was to either:
change property name (in model and database) or
change relationship name (Eg. productCategory )
It wasn't an error in my case. However, this happened to me when I was trying to open users.index, because while testing I've deleted some data from the 'STUDENTS' table and in the 'USERS' table, a foreign key ('student_id') represents the 'STUDENTS' table. So, now when the system tries to access the 'USERS' table in which foreign key ('student_id') is null since the value got deleted from the 'STUDENTS' table.
After checking for hours when I realise this, I insert the same data again in the 'STUDENTS' table and this resolved the issue.

Laravel Eloquent : belongsTo relationship - Error: Trying to get property of non-object

First time to try laravel eloquent relatioinstip
I know it's really simple but I am getting this error don't know what's wrong with it
I have 2 tables in data base, news and news_image
in database
Tables:
news
id | header | details
news_image
id | image | news_id
And have 2 models News , newsImage
newsImage model :
class newsImage extends Eloquant {
protected $table = 'news_image';
public function news()
{
return $this->belongsTo('News');
}
}
News model
class News extends Eloquent
{
protected $table = 'news';
public $timestamps = false;
public function image()
{
return $this->hasMany('newsImage');
}
}
The view:
foreach($news as $new)
<tr>
<td> {{$new->id}} </td>
<td> {{ $new->header}}</td>
<td> {{ $new->details }}</td>
</td> {{$new->news->image}}</td>
</tr>
when I run this it's get error :
Trying to get property of non-object (View: /var/www/html/clinics/app/views/news/index.blade.php)
Any ideas on what could be causing this error?
First, assuming what you are passing to your view is an array or Collection of News objects, you should probably be using $new->image to access the News Item relation. By defining the function image() in your News model, you can access the relation with either the ->image or ->image() calls. In either case, what you need to call is probably
$new->image->first()->image
To break that down:
->image gets the Collection of NewsImage relations
->first() gets the first item in the Collection
->image (the secone one) gets the image field from that NewsImage
If the Collection has more than one item, you can instead loop over it to get all of the images as shown in the other answer.
There are a couple things I would change:
In your News model, change the relationship from "image" to "images" since it's a one to many relationship. It just keeps your code clean.
Your foreach loop in your view should loop through all the news models, but remember that each news model has multiple images, so you should have another loop inside your existing loop to display the images, i.e. foreach ($new->images as $image)
#foreach ($news as $new)
<tr>
<td> {{$new->id}} </td>
<td> {{ $new->header}}</td>
<td> {{ $new->details }}</td>
<td>
#foreach ($new->images as $image)
{{ $image->image }}
#endforeach
</td>
</tr>
#endforeach

relationship and blade in laravel

I have 3 table as mentioned below.
Table 1(user):
id username password Name Age
Table 2(tasks):
id task_name description
Table 3(logs)
id user_id task_id date hours
Table Relationships:
user has_many logs
task has_many logs
logs belongs_to user
logs belongs_to task
what i am trying to achieve is to get the logs with the user Name, task Name, date and hours.
Controller:
return View::make('log.index')
->with('logs',log::all());
Blade template
#foreach($logs as $log)
<tr>
<td>{{$log->id}}</td>
<td>{{$log->users()->name}}</td>
<td>{{$log->tasks()->name}}</td>
<tr>
#endforeach
but unable to fetch users Name and Tasks name from the respective table. any help is appreciated.
A better way is to define inverse hasMany relation in your Model, as documented here
So in your logs model, probably you need to define:
class Log extends Eloquent {
protected $table = "logs";
public function user(){
return $this->belongsTo('User');
}
public function task(){
return $this->belongsTo('Task');
}
}
Then in your view you can either use :
$log->user()->first()->name
or even better, by using Dynamic Properties:
$log->user->name
$log->users() and $log->tasks() returns a query object. Below, each call returns the result which is the same as calling $log->users()->get() and $log->tasks()->get(). Because the relationships are many to many, you'll need to iterate over $log->users and $log->tasks to retrieve each record.
#foreach($logs as $log)
<tr>
<td>{{$log->id}}</td>
<td>
#foreach($log->users as $user)
{{$user->name}},
#endforeach
</td>
<td>
#foreach($log->tasks as $task)
{{$task->name}},
#endforeach
</td>
<tr>
#endforeach
If you want a specific user/task attached to a log you'll have to build a query.
#foreach($logs as $log)
<tr>
<td>{{$log->id}}</td>
<td>{{$log->users()->where('id', '=', $userID)->first()->name}} </td>
<td>{{$log->tasks()->where('id', '=', $taskID)->first()->name}} </td>
<tr>
#endforeach

Categories