Laravel | Id generated automatically

1

I am doing a news system and I want my url in the following way:

http://web.com/noticias/{id_generado}/

The {id_generado} is an id that I generate using the str_random(10) function.

The problem of the matter is: What happens if two news by chance generate the same {id_generado} ?

How can I check beforehand if that id has already been assigned to another news item and generate a new one? With a do-while?

    
asked by Dev. Joel 08.09.2017 в 01:00
source

2 answers

0

You can use a validation before saving
Manually Creating Validators

public function store(Request $request)
{
    $validator = Validator::make(['id_generado' => 165654165765456], [
        'id_generado' => 'required|unique:noticias|max:255'
    ]);

    if ($validator->fails()) {
        // Si falla la validacion ...
    }

    // Si no falla registras en la base ...
}
    
answered by 08.09.2017 в 02:47
0

It would be nice to use the do-while, one of the ways to apply it would be obtaining all the current ids (a single query) and comparing them with the generated one:

$idsActuales = Noticia::pluck('id_generado');

do {
    $idNuevo = str_random(10);
} while (in_array($idNuevo, $idsActuales));

// guardar noticia con nuevo id
Noticia::create(['id_generado' => $idNuevo]);
    
answered by 08.09.2017 в 04:10