Pull a belongsTo relation in Blade

Published 3 weeks ago by vinodsharma

I am trying to show task title into blade using belongsTo Relation. In Tinker its working Fine but in blade I am trying to show its not.

$allactivity->task->task_title And Below is the relation

   public function task()
    {
        return $this->belongsTo('Task');
    }
tykus
tykus
3 weeks ago (391,190 XP)

$allactivity as a variable name seems to suggest more than one Activity, i.e. a Collection rather than an Eloquent model?

vinodsharma

@tykus thnak you for your reply

@foreach($getAllactivities as $allactivity)
tykus
tykus
3 weeks ago (391,190 XP)

Is one of your $allactivity Eloquent instances associated with a non-existent Task? What error were you getting in the view?

vinodsharma

@tykus the errror is Trying to get property of non-object

tykus
tykus
3 weeks ago (391,190 XP)

So, like I said, one of your $allactivity instances has no task associated with it. You can use Laravel 5.5 optional() helper for these situations:

{{ optional($allactivity->task)->task_title }} 
vinodsharma

@tykus Thank you, I Checked all activity associated with a task and one thing I would like to tell you that I am using Custom helper function to Grab all Activity as given below


@foreach(Finder::getAllactivities() as $allactivity)
tykus
tykus
3 weeks ago (391,190 XP)

I don't think it is relevant how you gather the data; assuming that the non-object is a task

rumm.an

@vinodsharma Why dont you keep it very simple, This example might help you In Your Controller method:

$activity = Activity::with('task')->find(1);
return view('some.view', compact('activity'));

in your some/view.blade.php :

<h1> {{ $activity->task->task_title }} </h1>

Maybe this helps.

vinodsharma

@rumm.an Thank you, I konw this is possible that way also. But this view for every file and this is included in all files. So I am not think this is correct way to do so.

rumm.an

Give your relations and views. And tell me precisely what do you want to have as output?

tykus
tykus
3 weeks ago (391,190 XP)

I Checked all activity associated with a task

Are you really sure that every activity has a Task?

If you are using 5.5, the optional() helper method is the way to go here.It will identify to offending activity if nothing else.

Of course, this presumes that the problem is in the view, and not elsewhere in your code - a stack trace would confirm...

Please sign in or create an account to participate in this conversation.