How can I create a FaqPage with multiple questions?
richard-313 opened this issue ยท 2 comments
Hi there, thanks spatie for this awesome package!!
I have an array $faq with multiple questions and answers.
So I can loop this as follow:
foreach ($faqs as $key => $faq) { //$faq->question //$faq->answer }
So how can I create a Schema like the follow?
{ "@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [ { "@type": "Question", "name": "What is the return policy?", "acceptedAnswer": { "@type": "Answer", "text": "some text" } }, { "@type": "Question", "name": "Will I be charged sales tax for online orders?", "acceptedAnswer": { "@type": "Answer", "text":"some other text..."} } ] }
I know I can use
Schema::fAQPage() ->mainEntity([ ... ]);
and Schema::question()
But how does it work together?
Thanks in advanced ๐
Hey, the easiest will be array_map()
to go through your array and replace every entry with the corresponding schema type.
Schema::fAQPage()
->mainEntity(array_map(function($faq) {
return Schema::question()
->name($faq->question)
->acceptedAnswer(
Schema::answer()
->text($faq->answer)
)
}, $faqs));
The code isn't tested but should work. ๐
@Gummibeer thanks, it works!
Schema::fAQPage()
->mainEntity(
array_map(function($faq) {
return Schema::question()
->name($faq->question)
->acceptedAnswer(Schema::answer()
->text($faq->answer));
}, iterator_to_array($faqs))
);