Attempt to read property "degree" on null - laravel

i have created a profile where users can add their education fields.
when there is no value in the database it throws an error. how can i get rid of this ? Attempt to read property "degree" on null.
public function myEducations()
{
return $this->hasMany('App\Models\Education','user_id')->orderByDesc('endDate');
}
controller
public function myProfile(\App\Models\User $user)
{
$user = Auth::user();
$education = $user->myEducations->first();
return view('candidate.profile',compact('user','education'));
blade
{{ $education->degree }} - {{ $education->fieldOfStudy }}

If the users of you application are filling in their education details later only. You should ideally catch this condition when rendering your view. For example you could try the following:
#if ($education)
{{ $education->degree }} - {{ $education->fieldOfStudy }}
#else
<p>Education details not available</p>
#endif

You have to inspect in an if statement $education->degree is not null.
If not null, degree has value, this part will render.
Else, it doesn't have value so else block appears in template.
#if(null !== $education->degree)
{{ $education->degree }} - {{ $education->fieldOfStudy }}
#else
// there is no degree
#endif

Related

Laravel Auth Return

I created a function in users model to return permission and return as obj. but when i type {{ Auth::user()->permission()->outlineAgreements }} it said "htmlspecialchars() expects parameter 1 to be string, object given". How can i fix it ?
PS: inside test value is an array
"{"outlineAgreements":["view"],"purchaseOrder":["view"],"pwra":["view","create","update","delete"]}"
public function permission()
{
$permissions = auth()->user()->getAllPermissions()->pluck('name');
foreach ($permissions as $key => $value) {
$module = last(explode(" ", $value));
$action = current(explode(" ", $value));
$result[$module] = $result[$module] ?? [];
array_push($result[$module], $action);
}
return json_decode(json_encode($result));
}
Php is complaining about an object print. It expects that the data you are instructing it to print is a string.
Use dd to print out the return of the permissions method for debugging. This way you can see more clearly what data you are about to print out.
{{ dd(Auth::user()->permission()) }}
{{ dd(Auth::user()->permission()->outlineAgreements) }}
If your first box represents that payload data, and you need to access and print all outlineAgreements permissions, and it is an array, you can use implode:
{{ implode(', ', Auth::user()->permission()->outlineAgreements) }}
You can loop through that array too:
#foreach(Auth::user()->permission()->outlineAgreements as $permission)
{{ $permission }}
#endforeach
Hope it helped!

How to check that the variable is empty or not

This is my ProfileController:
public function index()
{
$id = Auth::user()->id;
$address = DB::table('addresses')->where('user_id', '=', $id)->get();
return view('/Pages.profile',['address'=>$address]);
}
I want this address from database to be printed on view, if the address is empty than a link to add address is shown..if it's not empty than display the address for particular users.
This is profile view:
#if(!empty($address))
#foreach($address as $row)
<p><strong>Address : </strong>{{ $row->house_no }}, {{ $row->location }}, {{ $row->landmark }}</p>
<p><strong> City : </strong>{{ $row->city }}</p>
<p><strong>State : </strong> {{ $row->state }}</p>
<p><strong>Pin Code : </strong>{{ $row->pin_code}}</p>
<a data-toggle="modal" data-target="#mod1">Edit address</a>
#endforeach
#else
Add address
#endif
Add address link does not show up even if the $address is empty. Any suggestions where I made the mistake
you can use isNotEmpty method.
From Docs
The isNotEmpty method returns true if the collection is not empty; otherwise, false is returned
so it should be like this:
#if($address->isNotEmpty())
#else
Add address
#endof
Laravel eloquent get() method will return you a collection
Use count() method to check if it doesn't have any elements like:
#if($address->count() !== 0)
#else
add address
#endif
Or
#if(!$address->isEmpty())

Laravel revisionable getting a list of all revisions by specific user

I'm using the VentureCraft/revisionable-package and it shows me in the ReadMe how to show the Revisions of a Model that has revisions:
#foreach($account->revisionHistory as $history )
<li>
{{ $history->userResponsible()->first_name }}
changed {{ $history->fieldName() }}
from {{ $history->oldValue() }}
to {{ $history->newValue() }}
</li>
#endforeach
But I want a list of All revisions that are done by a Specific user; how to achieve that? So I can show a History of Revisions that are done by one specific user.
I have never used this package. But based on what I see, you should be able to add this in your User model
public function revisions()
{
return $this->hasMany(\Venturecraft\Revisionable\Revision::class)
}
then
#foreach($user->revisions as $history )
<li>
{{ $user->first_name }}
changed {{ $history->fieldName() }}
from {{ $history->oldValue() }}
to {{ $history->newValue() }}
</li>
#endforeach
As you asked in the comments :
But I'm missing the Entity that's changed in that list.
(optional) I would implement an interface to my revisionable models with something like :
<?php
namespace App\Contracts;
interface RevisionableContract {
public function entityName();
}
Then in all my models that use the RevisionableTrait :
<?php
namespace App\Models;
class MyModel extend Eloquent implements RevisionableContract {
use RevisionableTrait;
// (required)
public function entityName(){
return 'My Entity name';
}
}
Finally :
#foreach($user->revisions as $history )
<li>
{{ $user->first_name }}
changed {{ $history->fieldName() }}
from {{ $history->oldValue() }}
to {{ $history->newValue() }}
on the entity {{ $history->historyOf()->entityName() }}
</li>
#endforeach
historyOf() may return false
Do you also have an idea how I can make a list of all revisions in desc-order with that info of the user?
From the migrations file, I can see that it has created_at and updated_at timestamps.
You have two possibilities :
In your view, you can directly order them on your collection like this :
#foreach($user->revisions->sortByDesc('created_at') as $history )
When you get a lot of revisions for a user, you will probably have performance issues and you will have to paginate them. From your controller, you will have to sort them and paginate them in your query instead of the collection.
public function index()
{
$user = User::find(1);
$revisions = $user->revisions()->orderBy('created_at')->paginate(15);
return view('your.view', compact('user', 'revisions'));
}
I could not use that package but it seems quite easy to understand. If you can show history of a user you should add this to your "User" entity:
public function history()
{
return $this->hasMany(\Venturecraft\Revisionable\Revision::class, 'user_id', 'id');
}
Or if you want to filter a specific morphable entity you should do it like this:
public function historyForUser(User $user)
{
return $this->morphMany(\Venturecraft\Revisionable\Revision::class, 'revisionable')->where('user_id' , '=', $user->getKey())->getResults();
}
I think that answer is corresponded for what you want to do.

laravel 5 show is returning empty query and not showing any data

i am new to laravel and i work on eloquent i want to send some data to view and show them like laravel documentation says so in my controller i wrote
public function show(PhoneBook $phoneBook)
{
return view('admin.phonebook.show',compact('phoneBook',$phoneBook));
}
and in the phonebook show view i wrote
<strong>id</strong> {{ $phoneBook->id }}<br>
<strong>calldate</strong> {{ $phoneBook->calldate }}<br>
<strong>description</strong> {{ $phoneBook->description }}
any idea why i receive empty query with no result with no errors and just the titles with no result in front of them i thank you if you can help me with this
Controller:
public function show($id)
{
$phonebook = Phonebook::find($id);
return view('admin.phonebook.show',compact('phonebook'));
}
Blade:
<strong>id</strong> {{ $phonebook->id }}<br>
<strong>calldate</strong> {{ $phonebook->calldate }}<br>
<strong>description</strong> {{ $phonebook->description }}
Try this:-
return view('admin.phonebook.show', compact('phoneBook'));
You can try 2 ways below to send data from Controller to View:
return view('admin.phonebook.show', compact('phoneBook'));
OR
return view('admin.phonebook.show')->with('phoneBook', $phoneBook);

laravel 5.2 entrust - show roles foreach user

My controller is
public function index()
{
$users = User::paginate(15);
return view('dash.users.index')->with(array('users' => $users));
}
in view i pass: {{ $item->roles }} and return all column as array, if i put {{ $item->roles->get('name') }}the table is blank, why?
I want to show user->roles->name foreach user
If it's an array, you should only simply use this:
{{ $item->roles['name'] }}
solved with nested foreach! #foreach($item->roles as $item) {{ $item['name'] }} #endforeach
inside my #foreach user
Thank you Mojtaba for the help!

Resources