Laravel将集合中的随机行插入分割文本

in my text i have some {{}} and i would like to replace them with random post from collection like with this code:

$latestHerbsInformation = \App\ContentCategories::find('14')->contents()->inRandomOrder()->get();

$split = explode('{{}}', $data->description);
foreach ($split as $sp) {
    $shuffled = $latestHerbsInformation->shuffle();
    $rand = $shuffled->take(1);
    echo $sp . $rand[0]->title;
}

in my code $rand = $latestHerbsInformation->take(1); return always same row on foreach statement, how can i change it to get random

You can chain first() off shuffle to get a single element:

$rand = $latestHerbsInformation->shuffle()->first()

when you shuffle() the $latestHerbsInformation it gives an array because the contents of it is an array. so you must do first() on it to not give you a collection. But make sure that the first() method comes after take(1) method. or you can limit the result by limit(1) method. so your code should look something like this:

$latestHerbsInformation = \App\ContentCategories::find('14')->contents()->inRandomOrder()->get();

$split = explode('{{}}', $data->description);
foreach ($split as $sp) {
    $rand = $latestHerbsInformation->shuffle()->take(1)->first();

    echo $sp . $rand->title;
}

and this way you do not need a key for $rand to access its properties.

or you can do it with limit() instead:

foreach ($split as $sp) {
    $rand = $latestHerbsInformation->shuffle()->limit(1)->first();

    echo $sp . $rand->title;
}