Laravel中的匿名函数vs String文字控制器

What is difference between the fellowing two route codes?

One is without controller ans seccond one has a controller:

  • Version 1

    Route::get('/', function () {
        return view('front/index');
    })
    
  • Version 2

    Route::get ('/main', 'MainController@index');
    

Version 1 Returns route ‘/‘ along with a view found in ‘front/index’

Version 2 Returns route at ‘/main’

First one is returning a view directly with a function, so when you hit route '/' it will return view front/index. front->index.blade.php

Another one is calling Controller 'MainController' which has function index:

public function index() {
    return view('front.index);
}

which will return index function from controller 'MainController' when you hit /main url. They are doing same thing but using Controller helps organize code and stuff much easier for you in a long run

hope it helps

In Laravel, you can totally skip controllers and do the task of performing business logic and generating the view in the routes, like:

Route::get('/users',function()
{
    $users = User::All();   //select * from users
    return view('users')->with('users', $users);
}

So, here to serve the request /users, we didn't use controller at all and you can very well do this for handling all requests in your application, both get and post. Laravel allows you to do your job there in a closure (function(){}), instead of binding it to a controller. Anyway, it lets you, but you'd better avoid it.

But then, if your application is large and have 100+ url's with complex business logic then imagine putting everything in one routes/web.php. It will totally make it criminally dirty and whole purpose of MVC architecture will be defeated. Hence what we usually do is, reserve web.php for routing only and write all business logic (along with generation of views inside controllers) .

In Route::get() you only should go with your 'routing' and nothing more.

There is no reason for you to use callbacks in Route (unless for testing or some trivial requests). So, better to avoid this:

Change this code:

Route::get("/", function(){
    return view("front.index");
});

To this:

Route::get ('/', 'MyController@index');

And within your controller:

class MyController extends Controller
{
   function index()
   {
      return view("front.index");
   }
}

Hope it helps.