0
0
Laravelframework~5 mins

Controller methods and actions in Laravel

Choose your learning style9 modes available
Introduction

Controllers help organize your code by handling user requests and sending responses. Methods inside controllers define what happens for each action.

When you want to handle a form submission and save data.
When you need to show a list of items from the database.
When you want to update or delete a resource based on user input.
When you want to separate your app logic from routes for cleaner code.
Syntax
Laravel
class ExampleController extends Controller {
    public function actionName() {
        // code to handle the action
    }
}

Each method inside a controller is called an action.

Actions usually return a view, redirect, or JSON response.

Examples
This method shows a list of users by returning a view.
Laravel
class UserController extends Controller {
    public function index() {
        return view('users.index');
    }
}
This method handles saving a new post from form data.
Laravel
class PostController extends Controller {
    public function store(Request $request) {
        // save new post
    }
}
This method deletes a product using its ID.
Laravel
class ProductController extends Controller {
    public function destroy($id) {
        // delete product by id
    }
}
Sample Program

This controller has two methods: one returns a simple greeting, the other greets a user by name.

Laravel
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class GreetingController extends Controller
{
    public function hello() {
        return 'Hello, welcome to Laravel!';
    }

    public function greetUser($name) {
        return "Hello, {$name}! Nice to see you.";
    }
}
OutputSuccess
Important Notes

Controller methods should be kept simple and focused on one task.

Use dependency injection to get request data or services inside methods.

Always return a response from controller methods, like a view or string.

Summary

Controllers group related actions to handle requests.

Each method inside a controller is an action that does something.

Actions return responses like views, redirects, or strings.