The controller and Model are part of the MVC (Model-View-Controller) software design commonly used to implement user interfaces, data, and controlling logic. It emphasizes a separation between the software’s business logic and display.

MVC Pattern:

Controller:

The controller contains logic that updates the model and/or view in response to input from the users of the app.

So for example, a shopping list could have input forms and buttons that allow us to add or delete items. These actions require the model to be updated, so the input is sent to the controller, which then manipulates the model as appropriate, which then sends updated data to the view.

You might however also want to update the view to display the data in a different format, e.g., change the item order to alphabetical, or lowest to highest price. In this case, the controller could handle this directly without needing to update the model.

Artisan command to create a controller

php artisan make: controller ShoppingController

OR

Resource controller with the default method for CRUD operation

php artisan make: controller PhotoController --resource

Specify the resource model as well

php artisan make: controller PhotoController --model=Photo --resource

Form Request

php artisan make: controller PhotoController --model=Photo --resource --requests

Let’s take a look at an example of a basic controller. Controllers have any number of public methods that will respond to incoming requests.

 User::findOrFail($id)
       ]);
   }
}

Define the route for a particular controller

use App\Http\Controllers\UserController;
Route::get('/user/{id}', [UserController::class, 'show']);

// Resource controller
Route::resource('users', UserController::class);

Partial Resource Route

Route::resource('photos', PhotoController::class)->only([
   'index', 'show'
]);

Naming routes

Route::resource('photos', PhotoController::class)->names([
   'create' => 'photos.build'
]);

API Resource route

Route::apiResource('photos', PhotoController::class);

Define middleware for the controller

Route::get('profile', [UserController::class, 'show'])->middleware('auth');

OR

class UserController extends Controller
{
   /**
    * Instantiate a new controller instance.
    */
   public function __construct()
   {
       $this->middleware('auth');
       $this->middleware('log')->only('index');
       $this->middleware('subscribed')->except('store');
   }
}

You can call the existing controller’s method within the controller

 $this->MyCustomFunction();

Dependency Injection in the controller’s method


Method injection

name;
       // Store the user...
       return redirect('/users');
   }
}

Model:

The Model component corresponds to all the data-related logic that the user works with. This can represent either the data that is being transferred between the View and Controller components or any other business logic-related data. It can add or retrieve data from the database. It responds to the controller’s request because the controller can’t interact with the database by itself. The model interacts with the database and returns the required data to the controller.

Laravel includes Eloquent, an object-relational mapper (ORM) that makes it enjoyable to interact with your database.

To get started, let’s create one model that is basically by default stored in app/Models.

Generate new model

php artisan make: model Flight

You can create migration files as well

php artisan make: model Flight --migration

Other types of classes that you can create

# Generate a model and a FlightFactory class...
php artisan make: model Flight --factory
php artisan make: model Flight -f
# Generate a model and a FlightSeeder class...
php artisan make: model Flight --seed
php artisan make: model Flight -s
# Generate a model and a FlightController class...
php artisan make: model Flight --controller
php artisan make:model Flight -c
# Generate a model, FlightController resource class, and form request classes...
php artisan make: model Flight --controller --resource --requests
php artisan make: model Flight -crR
# Generate a model and a FlightPolicy class...
php artisan make: model Flight --policy
# Generate a model and a migration, factory, seeder, and controller...
php artisan make: model Flight -mfsc
# Shortcut to generate a model, migration, factory, seeder, policy, controller, and form requests...
php artisan make: model Flight --all
# Generate a pivot model...
php artisan make: model Member --pivot
php artisan make: model Member -p

You can easily inspect the model by

php artisan model: show Flight

The basic structure of the model



You can define various variables for model


Create unique UUID

use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
   use HasUuids;
   // ...
}
$article = Article::create(['title' => 'Traveling to Europe']);
$article->id; // "8f8e8478-9035-4d23-b9a7-62f4d2612ce5"

Retrieving model

use App\Models\Flight;
foreach (Flight::all() as $flight) {
   echo $flight->name;
}

Building Query

$flights = Flight::where('active', 1)
              ->orderBy('name')
              ->take(10)
              ->get();

Fresh/Refreshing Model

$flight = Flight::where('number', 'FR 900')->first();
$freshFlight = $flight->fresh(); // will not effect $flight
$flight = Flight::where('number', 'FR 900')->first();
$flight->number = 'FR 456';
$flight->refresh();
$flight->number; // "FR 900"

Chunking Result

use App\Models\Flight;
use Illuminate\Database\Eloquent\Collection;
Flight::chunk(200, function (Collection $flights) {
   foreach ($flights as $flight) {
       // ...
   }
});

Not found exception

$flight = Flight::findOrFail(1);
$flight = Flight::where('legs', '>', 3)->firstOrFail();

Mass Assignment

use App\Models\Flight;
$flight = Flight::create([
   'name' => 'London to Paris',
]);

Insert

$flight = Flight::create([
   'name' => 'London to Paris',
]);

Update

use App\Models\Flight;
$flight = Flight::find(1);
$flight->name = 'Paris to London';
$flight->save();

Delete Model

use App\Models\Flight;
$flight = Flight::find(1);
$flight->delete();

Soft Delete Model

restore(); // The restore method will set the model's deleted_at column to null:
$flight->forceDelete(); // Permanently Delete model
?>

Support On Demand!

Laravel