Skip to main content

Controller

  • stored in the app/Http/Controllers directory
  • Instead of defining all of request handling logic in the web.php file, for larger projects, it is encouraged to organize using "controller" classes
  • Controllers can group related request handling logic into a single class

Create a simple controller

  • php artisan make:controller HomeController
  • a HomeController file is created at app/Http/Controllers folder, open it and edit the following
class HomeController extends Controller{
public function home(){ //home method of the HomeController class
return view('home.index');
}
public function contact(){ //contact method of the HomeController class
return view('home.contact');
}
}
  • go to web.php file and change the following
use App\Http\Controllers\HomeController;
Route::get('/',[HomeController::class, 'home']);
Route::get('/contact',[HomeController::class, 'contact']);

Create a resource controller

  • a resource controller has CRUD actions already defined (Create, Read, Update, Delete)
php artisan make:controller PostController --resource //--resource will generate CRUD action automatically
  • a PostController file is created at app/Http/Controllers folder, open it and edit the following
use App\Models\BlogPost;

class PostController extends Controller{
public function index(){
$posts = BlogPost::all();
return view('posts.index',['posts' => $posts]);
}
public function show($id){
$post = BlogPost::find($id);
return view('posts.show',['post' => $post]);
}
public function create(){}
public function store(Request $request){}
public function edit($id){}
public function update(Request $request, $id){}
public function destroy($id){}
}
  • go to web.php file and change the following
use App\Http\Controllers\PostController;

Route::resource('posts',PostController::class); //for all actions
Route::resource('posts',PostController::class)->only(['index','show']); //or we can limit to only certain actions needed