Write a PHP program to create a url shortener laravel (1)
Write a PHP program to create a url shortener laravel (1)
laravel.
First, make sure you have Laravel installed on your system. If not, you can install it using Composer.
cd url-shortener
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password
use App\Http\Controllers\UrlShortenerController;
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Url;
return view('index');
$request->validate([
]);
$inputUrl = $request->input('url');
$code = Url::generateUniqueShortCode();
Url::create([
]);
return redirect($url->original_url);
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use HasFactory;
$code = Str::random(6);
$code = Str::random(6);
}
return $code;
Create index.blade.php:
<!DOCTYPE html>
<html>
<head>
<title>URL Shortener</title>
</head>
<body>
@if (session('shortened'))
@endif
@csrf
<button type="submit">Shorten</button>
</form>
</body>
</html>
Create a new PHP file with an appropriate name for your migration. For example,
you could name it something like 2024_02_21_123456_create_urls_table.php to
follow Laravel's migration naming convention.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* @return void
*/
$table->id();
$table->string('original_url');
$table->string('short_code')->unique();
$table->timestamps();
});
/**
* @return void
*/
Schema::dropIfExists('urls');
That's it! You've created a basic URL shortener in Laravel. You can now run your
Laravel application using: