Reputation: 33
In Laravel - Is there a way to return a diffent collection if a relationship does not return any values?
Eg.
class Topic
{
public function questions()
{
return $this->hasMany(Questions::class);
}
}
This return the questions for the topic. But the required behaviour I need is if I query $topic->questions()
is for it to return me a list of
return Questions::get()->whereNull('topic_id')
Anyone know how I can accomplish this?
The migrations:
Schema::create('topics', function (Blueprint $table) {
$table->increments('id');
$table->string('topic')->index();
$table->timestamps();
});
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('topic_id')
->nulluble()
->comment('link to the topic table');
$table->foreign('topic_id', 'fk_topic_question')
->references('id')
->on('topics')
->onDelete('cascade');
$table->string('question')->nullable();
$table->timestamps();
});
And then default questions seed example:
$data = [
[
'question'=>'default questions 1'
],
[
'question'=>'default questions 2'
]
];
Questions::insert($data);
Upvotes: 0
Views: 1870
Reputation: 33
I settled on a interim solution (bit hacky but does what I need) :
public function getQuestions()
{
if ($this->questions()->exists()) {
return $this->questions;
} else {
return Question::all();
}
}
then I use $topic->getQuestions()
instead of $topic->questions()
Upvotes: 0
Reputation: 2656
You can use optional
helper function:
https://laravel.com/docs/8.x/helpers#method-optional
create a topic for default questions and relate defualt questions to this topic and then you can use this:
$questions = optional($preferTopic,$defaultTopic)->questions;
Upvotes: 1