Support the ongoing development of Laravel.io →
Requests Database Eloquent
Last updated 2 years ago.
0
Route::post('/',function(){

  //We first define the Form validation rule(s)
  $rules = array(
    'link' => 'required|url'
  );

  //Then we run the form validation
  $validation = Validator::make(Input::all(),$rules);

  //If validation fails, we return to the main page with error info
  if($validation->fails()) {
    return Redirect::to('/')
        ->withInput()
        ->withErrors($validation);
  } else {
    //Now let's check that if we have the link already in our database, if so we get the first result
    $link = Link::where('url','=',Input::get('link'))
      ->first();
    //If we have the URL saved in our database already, we provide that information back to view.
    if($link) {
      return Redirect::to('/')
        ->withInput()
        ->with('link',$link->hash);
    //Else we create a new unique URL
    } else {
      //First we create a new unique Hash
      do {
        $newHash = Str::random(6);
      } while(Link::where('hash','=',$newHash)->count() > 0);

      //Now we create a new database record
      Link::create(array(
        'url' => Input::get('link'),
        'hash'  => $newHash
      ));

      //And then we return the new shortened URL info to our action
      return Redirect::to('/')
        ->withInput()
        ->with('link',$newHash);
    }
  }
});

route code

Last updated 2 years ago.
0

I suggest using named routes and controllers this code is really unreadable.

Route::get('/', array('as' => 'home', 'uses' => 'Controller@getHome'));
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

sger sger Joined 15 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.