How to migrate Slim to Laravel API

Elihai David Vanunu
2 min readOct 26, 2020

I have got a project built with Slim PHP framework. I thought maintain Slim project would be very heavy and slow. I decided using power of Laravel would be great. So I want to introduce you a simple way to use Laravel routes API with old methods of Slim framework.

  1. Old Slim code example. Assume we have one route of sayHello.
$app = new Slim();$app->get('hello','sayHello');function sayHello(){
echo "Hi there";
}

2. Than we want use Laravel route to call this method, without change function itself. So create dummy Slim object:

class SlimDummy {
public function get($uri, $func){
Route::get($uri, function() use($func){
$func();
});
}
}
$app = new SlimDummy(); // Replace only this line$app->get('hello','sayHello'); //Don't touch old codefunction sayHello(){
echo "Hi there";
}

Walla! we have Laravel route, calling legacy slim function.

But wait what with parameters?

3. Add parameters to function call, you can add as many as desired parameters. (Function with less parameters not get hurts at all)

class SlimDummy {    public function get($uri, $func){        Route::get($uri, function($arg1 = null,
$arg2 = null,
$arg3= null) use($func){
$func($arg1, $arg2, $arg3);
});
}
}

Ok great! But there is one problem, Laravel url parameters are different than in Slim routes.

4. Fix urls to be Laravel correct.

For example, with Laravel we put route parameter: {param}

With Slim we put it like: :param.

So create a fixer function with regex.

class SlimDummy {    public function get($uri, $func){        Route::get($this->fixUri($uri), 
function($arg1 = null,
$arg2 = null,
$arg3= null) use($func){
$func($arg1, $arg2, $arg3);
});
}
private function fixUri($uri){ $fixed = preg_replace("/\(\:([A-z]+)\)/", "{\$1?}" , $uri); return preg_replace("/:([A-z]+)/", "{\$1}" , $fixed); }}

Hi, What with other HTTP methods?

5. Add other method to your class, and this is whole code:

https://pastebin.com/embed_iframe/6KnT7wU

--

--