LARAVEL

CRUD Using models in controllers


Using models in controllers is a common practice in Laravel applications. Models represent the data of your application and encapsulate the business logic related to that data. Controllers, on the other hand, act as an intermediary between the HTTP requests coming from the routes and the models responsible for handling data manipulation.

Below is an example of how you can use models in controllers:

 

1. Create a Model:

First, create a model using the Artisan command:

php artisan make:model User

This will create a User.php file in the app\Models directory by default.

 

2. Define Model Logic:

Define the logic for your model in User.php. This may include relationships with other models, attribute casting, accessors, mutators, and any other business logic related to the user data.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    // Model properties and methods
}

 

3. Create a Controller:

Next, create a controller using the Artisan command:

php artisan make:controller UserController

This will create a UserController.php file in the app\Http\Controllers directory.

 

4. Use Model in Controller:

Inside your controller, you can use the model to perform various operations such as fetching data, creating new records, updating records, and deleting records. Here's an example:

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index()
    {
        $users = User::all();
        return view('users.index', ['users' => $users]);
    }

    public function show($id)
    {
        $user = User::find($id);
        return view('users.show', ['user' => $user]);
    }

    public function store(Request $request)
    {
        $user = new User();
        $user->name = $request->input('name');
        $user->email = $request->input('email');
        $user->save();

        return redirect()->route('users.index');
    }

    public function update(Request $request, $id)
    {
        $user = User::find($id);
        $user->name = $request->input('name');
        $user->email = $request->input('email');
        $user->save();

        return redirect()->route('users.show', $id);
    }

    public function destroy($id)
    {
        $user = User::find($id);
        $user->delete();

        return redirect()->route('users.index');
    }
}

 

Conclusion:-

In Laravel, controllers interact with models to handle data manipulation logic. By separating concerns, you can keep your code organized and maintainable. Controllers handle HTTP requests and responses, while models encapsulate the business logic and database interactions. This separation of concerns follows the MVC (Model-View-Controller) architecture pattern, which is a fundamental concept in Laravel development.


LARAVEL