Skip to main content

Overview

The Link model represents shortened URLs in LaraCMS’s URL shortener feature. Each link belongs to a user and tracks URL redirects for analytics and marketing purposes. Namespace: App\Models\Link File: app/Models/Link.php:7

Properties

Mass assignment

This model uses $guarded = [], meaning all attributes are mass-assignable. Based on the migration schema, the model likely contains:
user_id
integer
required
The ID of the user who created the link
slug
string
required
The short URL slug (e.g., “abc123”)
url
string
required
The original full URL to redirect to
clicks
integer
default:"0"
Number of times the link has been clicked

Relationships

user()

Belongs to relationship with the User model. Returns: BelongsTo<User>
// Get the user who created a link
$link = Link::find(1);
$creator = $link->user;

// Get all links created by a user
$user = User::find(1);
$userLinks = $user->links;

Usage examples

use Illuminate\Support\Str;

$link = Link::create([
    'user_id' => auth()->id(),
    'slug' => Str::random(6),
    'url' => 'https://example.com/very/long/url',
    'clicks' => 0
]);

Tracking clicks

$link = Link::where('slug', 'abc123')->firstOrFail();
$link->increment('clicks');

// Redirect to original URL
return redirect($link->url);
// Get user's most clicked links
$topLinks = Link::where('user_id', auth()->id())
    ->orderBy('clicks', 'desc')
    ->take(10)
    ->get();

// Get recent links
$recentLinks = Link::with('user')
    ->latest()
    ->paginate(20);

// Check if slug exists
$slugExists = Link::where('slug', 'abc123')->exists();

Generating unique slugs

function generateUniqueSlug($length = 6) {
    do {
        $slug = Str::random($length);
    } while (Link::where('slug', $slug)->exists());
    
    return $slug;
}

$link = Link::create([
    'user_id' => auth()->id(),
    'slug' => generateUniqueSlug(),
    'url' => $request->url
]);

Database schema

Based on the migration file 2025_09_06_175723_create_links_table.php, the links table contains:
  • id - Primary key
  • user_id - Foreign key to users table
  • slug - Short URL identifier (string, unique)
  • url - Original URL (text)
  • clicks - Click counter (integer, default 0)
  • created_at - Timestamp
  • updated_at - Timestamp

URL shortener feature

The Link model is used by the admin URL shortener tool at /admin/url-shortener. See the URL tools documentation for more details on the user interface.

User model

View User model documentation

URL tools

Learn about URL shortener admin interface

Build docs developers (and LLMs) love