public function getRouteKeyName() {
return 'slug';
}
Y luego desde cualquier view:
<a href="{{ route('categories.show', $category) }}">... </a>
public function getRouteKeyName() {
return 'slug';
}
<a href="{{ route('categories.show', $category) }}">... </a>
Crear en App/Exception/InvalidEntrySlugException.php:
<?php
namespace App\Exceptions;
use App\Entry;
use Exception;
use Throwable;
class InvalidEntrySlugException extends Exception {
private $entry;
public function __construct(Entry $entry, $message = "", $code = 0, Throwable $previous = null)
{
$this->entry = $entry;
parent::__construct($message, $code, $previous);
}
public function render()
{
return redirect($this->entry->getUrl());
}
}
?>
En App/providers/RouteServiceProvider.php
$entry = Entry::findOrFail($id);
if ($entry->slug."-".$entry->id === $value) {
return $entry;
}
else {
// forzará a q se vaya a la url correcta por si se pone lo-xxxx-viento-se-llevo-3
throw new InvalidEntrySlugException($entry);
}
public function boot() {
parent::boot();
// para hacer que coga el id del slug por si se cambie el slug tire siempre del id
Route::bind('entry', function($value) {
$arrAux = explode("-", $value);
$id = end($arrAux);
return Entry::findOrFail($id);
});
}
'strict' => false,
$table->string('slug');
// crear un mutator para el slug
public function setTitleAttribute($value) {
$this->attributes['title'] = $value;
$this->attributes['slug'] = Str::slug($value);
}
// para q el controller busque por ese campo en vez de por el id
public function getRouteKeyName() {
return 'slug';
}
// esto es para q desde las views sea más cómodo y no haya q escribir tanto
public function getUrl() {
return url('entries/'.$this->slug.'-'.$this->id);
}
<a href="{{ $item->getUrl() }}">
{{ $item->title}}
</a>
php artisan migrate:fresh --seed
public function generarSlug($titulo) {
$slug = str_slug($titulo);
$arrAux = Pelicula::select('slug')->where('slug', $slug)->get();
$cont = 1;
while (count($arrAux) == 1) {
$slug .= "-".$cont;
$arrAux = Pelicula::select('slug')->where('slug', $slug)->get();
$cont++;
}
return $slug;
}
// Para llamarlo dentro del mismo controller
$slug = $this->generarSlug($request->get("titulo")." ".$request->get("anno"));