I have two models [The relation is one-many / Category-Trip]:
Category Model Code:
class Category extends Model
{
use HasFactory;
protected $fillable = [
'id',
'category_name',
'category_desc',
'category_img',
];
public function trip() {
return $this->hasMany(Trip::class);
}
}
Trip Model Code:
class Trip extends Model
{
use HasFactory;
protected $fillable = [
'name',
'description',
'max_visitors',
'price',
'date',
'image',
'guide_id',
'category_id',
];
public function category()
{
return $this->belongsTo(Category::class);
}
}
when I use this code, I will get this error:
TypeError Symfony\Component\HttpFoundation\Response::setContent(): Argument #1 ($content) must be of type ?string, Illuminate\Database\Eloquent\Relations\BelongsTo given, called in C:\Users\Orange\Desktop\ON GITHUB\Tours-Booking\vendor\laravel\framework\src\Illuminate\Http\Response.php on line 72
$trip = Trip::findOrFail(1);
return $trip->category();
But when write this without paratheses, i will not get this error, what is the problem?
$trip = Trip::findOrFail(1);
return $trip->category;
CodePudding user response:
As a user explained (but not fully):
You are returning a relationship in your controller, but that is not valid (based on the error). Because BelongsTo
cannot be serialized to a string
, it tries to return the BelongsTo
object, hence giving you that error (look, it is saying it is wanting null
or a string
, but you are returning BelongsTo
).
When you do $model->relation
(without ()
), that means it will try to get all the data that satisfies the relation and store it as a Category
in $model->relation
(because it is a BelongsTo
), but when you use $model->relation()
you creating a query
so you can query the relation with whatever you want/need, like $model->relation()->where('status', 'Active')->get()
...
You have 2 solutions: either return $trip->category
(it is going to be a Category
object/model) or $trip->category()->get()
or any query but use ->get()
(will return a Collection
) or ->first()
(will return a Category
model) at the end...
Read the documentation again so you understand better now: Relationships and First vs Get and BelongsTo documentation.
CodePudding user response:
When you call the method its instantiating a eloquent instance in which you can extend it to a query which will give you a Category model
example (this might not be the most appropriate example)
$trip = Trip::findOrFail(1);
return $trip->category()->where('category_name', 'something')->first();
And the latter returns a collection.