Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

davidgrzyb/laravel-url-shortener

9 stars
3 code files
View davidgrzyb/laravel-url-shortener on GitHub

composer.json

Open in GitHub
{
//
"require": {
//
"livewire/livewire": "^2.3"
},
//
}

app/Http/Livewire/CreateLink.php

Open in GitHub
use App\Models\Link;
use Livewire\Component;
use Illuminate\Support\Str;
use Vinkla\Hashids\Facades\Hashids;
 
class CreateLink extends Component
{
public $url;
public $slug;
 
protected $rules = [
'url' => 'required|url|max:255',
'slug' => 'nullable|alpha_dash|unique:links,slug|min:3|max:100',
];
 
public function updated($property)
{
$this->validateOnly($property);
}
 
public function saveLink()
{
$this->validate();
 
$link = Link::create([
'url'=> $this->url,
'slug' => $this->slug ?? Str::random(20),
'user_id' => auth()->user()->id,
]);
 
if (! $this->slug) {
$link->update(['slug' => Hashids::encode($link->id)]);
}
 
return redirect(route('links'));
}
 
public function resetForm()
{
$this->reset();
$this->resetValidation();
}
 
public function render()
{
return view('livewire.create-link');
}
}

resources/views/livewire/create-link.blade.php

Open in GitHub
<div>
<form wire:submit.prevent="saveLink">
<div class="mb-4">
<label for="url">URL</label>
<x-input wire:model.lazy="url" id="url" class="block my-2 w-full" type="text" placeholder="https://google.ca" required autofocus />
@error('url') <span class="text-red-500">{{ $message }}</span> @enderror
</div>
 
<div class="mb-4">
<label for="slug">Slug</label>
<x-input wire:model.lazy="slug" id="slug" class="block my-2 w-full" type="text" placeholder="my-new-link" />
@error('slug') <span class="text-red-500">{{ $message }}</span> @enderror
</div>
 
<div class="flex justify-end">
<button
wire:click="resetForm"
type="button"
class="inline-flex items-center px-4 py-2 bg-gray-400 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-400 active:bg-gray-500 focus:outline-none focus:border-gray-500 focus:ring ring-gray-300 disabled:opacity-25 transition ease-in-out duration-100 mr-2"
>
Reset
</button>
<button
type="submit"
class="inline-flex items-center px-4 py-2 bg-indigo-500 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-indigo-700 active:bg-indigo-900 focus:outline-none focus:border-indigo-900 focus:ring ring-indigo-300 disabled:opacity-25 transition ease-in-out duration-100"
>
Create
</button>
</div>
</form>
</div>

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.