Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel how to create empty relationship?

Tags:

php

laravel

I have a condition inside a relationship where if the user is logged in it will return the relation and if not i want it to return empty relationship. here is what i want :

public function dummy()
{
    return (auth()->user()) ? $this->hasOne(blah::class) : emptyrelationship();
}
like image 278
m_elbardeny Avatar asked May 16 '17 12:05

m_elbardeny


People also ask

How do you make a relationship in laravel?

A typical example of such a relationship is a user with many roles, where the roles are shared by other users as well. For instance, more than one user may have the role of "Admin". In defining this relationship, we need three database tables: users, roles, and role_user.

What is hasMany in laravel?

hasMany relationship in laravel is used to create the relation between two tables. hasMany means create the relation one to Many. For example if a article have comments and we wanted to get all comments of the article then we can use hasMany relationship .

Does laravel have one relation?

hasOne relationship in laravel is used to create the relation between two tables. hasOne means create the relation one to one. For example if a article has comments and we wanted to get one comment with the article details then we can use hasOne relationship or a user can have a profile table.


1 Answers

You should check with DD() what is being returned as you like.

If there's no data for the relationship to show, it will just return no data.

like image 123
Staafsak Avatar answered Oct 06 '22 03:10

Staafsak