Random data in Blade / Laravel 5.1

2

I want to generate random data in my views, specifically I want to go through the results of a query and each one assign a different color, all this in my views of Blade (Laravel) .

Something like this (similar to what I want to do):

$array = array('success', 'danger', 'info', 'warning');
$rand = rand(0,3);
echo $array[$rand];

Sure, all this in Blade .

    
asked by Mario Montano 12.11.2016 в 03:05
source

4 answers

1

You must keep in mind that Blade is not just a template engine and a kind of basic php wrapper, so managing business logic in Blade is not the best idea.

To keep this in mind, Laravel no longer necessarily applies the MVC pattern 100%, that's part of the past, so the controller would not be the ideal place for that code either. You can place it in another layer as a service or a helper.

In any case, if you definitely want to do it with Blade in sight, you could do this:

{{ array_rand(['success', 'danger', 'info', 'warning']) }}

Or you can put together another similar solution with shuffle ()

    
answered by 13.11.2016 в 15:43
0

Following the principle of a single responsibility and the MVC design pattern. The view should only be responsible for representing the data that the controller sends, not generating their own.

Then from your controller you have to assign the colors and simply use them in your view, say for example that you get users and you add color to each one. An approach to achieve what you are looking for in your template would be the following:

@foreach ($users as $user)
    <p style='color: {{ $user->color }} '> {{ $user->nombre }}</p>
@endforeach
    
answered by 12.11.2016 в 22:32
0

You can also use a specific library for this:

https://github.com/fzaninotto/Faker

It is a library that in a very simple way allows you to create multiple options and texts.

Installation is simple and use, much more.

You can use it for yours and to create more random data.

    
answered by 14.11.2016 в 10:24
0

Thank you all for answering. I did the following:

// CategoriesController

    $categories = Category::orderBy('id', 'ASC')->paginate(5);
    $colors = array('success', 'danger', 'info', 'warning');
    shuffle($colors);

    return view('admin.categories.index')->with(['categories' => $categories, 'colors' => $colors]);

// Categories / index.blade.php

"label label-{{ $colors[rand(0,3)] }}">{{ $category->name }}

With this solve, I wanted those random colors, I did not want to save them in the BD. (Comment if it seems right or if you have some other idea).

    
answered by 13.11.2016 в 17:09