版权声明:http://www.itchuan.net https://blog.csdn.net/sinat_37390744/article/details/88555536
1、routes中
Route::get('/','HomeController@index');
Route::get('{url_code}','HomeController@shortened');
Route::post('/','HomeController@store');
2、数据库Urls
Schema::create('urls',function (Blueprint $table){
$table->increments('id');
$table->string('url');
$table->string('shortened',5);
$table->timestamps();
});
3、Url模型
public static function get_unique_short_url(){
$shortened = base_convert(rand(10000,99999),10,36);
$record = \App\Url::where('shortened','=',$shortened)->first();
if(!empty($record)){
static::get_unique_short_url();//如果数据库中已有数据记录,则重新调用
}
return $shortened;
}
4、view中
<h1>短链生成器</h1>
<div class="col-lg-8">
{{Form::open(['url'=>'/'])}}
<div class="input-group">
{{Form::text('url','',['class'=>'form-control input-lg','placeholder'=>'请输入您的网址'])}}
<span class="input-group-btn">
{{Form::submit('缩短','',['class'=>'btn btn-success btn-lg'])}}
</span>
</div><!-- /input-group -->
{{Form::close()}}
<br><br>
<h2>您的短链:<a href="/{{$shortened}}" target="_blank">http://xxx.cn/{{$shortened}}</a></h2>
</div>
5、Home控制器
public function store(){
$url = \request('url');
$this->validate(\request(),[
'url'=>'required|url'
]);
$record = \App\Url::where('url',$url)->first();
//如果数据库中已经有记录,则直接返回数据库中的记录
if($record){
$shortened = $record->shortened;
return view('/home/result',compact(['shortened']));
}
//如果数据库中没有记录,则生成随机短链,将原本网址和随机短链存入数据库
$shortened = \App\Url::get_unique_short_url();
\App\Url::create(['url'=>$url,'shortened'=>$shortened]);
return view('/home/result',compact(['shortened']));
}
//用户在首页点击短网址时,根据传递的参数短链 4glj 在数据库中寻找,如果数据库中有记录,则直接跳转到原本的网址,否则返回首页
public function shortened($url_code){
$shortened = \App\Url::where('shortened',$url_code)->first();
if(is_null($shortened)){
return redirect('/home/index');
}
return redirect($shortened->url);
}
6、项目地址