{"id":10385,"date":"2024-05-24T05:11:37","date_gmt":"2024-05-24T05:11:37","guid":{"rendered":"https:\/\/www.bacancytechnology.com\/qanda\/?p=10385"},"modified":"2024-05-24T05:16:18","modified_gmt":"2024-05-24T05:16:18","slug":"laravel-controller-vs-model","status":"publish","type":"post","link":"https:\/\/www.bacancytechnology.com\/qanda\/laravel\/laravel-controller-vs-model","title":{"rendered":"Laravel Controller vs. Model &#8211; Explained"},"content":{"rendered":"<p>The controller and Model are part of the <strong>MVC (Model-View-Controller)<\/strong> software design commonly used to implement user interfaces, data, and controlling logic. It emphasizes a separation between the software&#8217;s business logic and display.<\/p>\n<h3>MVC Pattern:<\/h3>\n<p><img decoding=\"async\" class=\"alignnone size-full wp-image-10386\" src=\"https:\/\/assets.bacancytechnology.com\/qanda\/wp-content\/uploads\/2024\/05\/24044916\/laravel-mvc.jpg\" alt=\"\" width=\"768\" height=\"514\" srcset=\"https:\/\/assets.bacancytechnology.com\/qanda\/wp-content\/uploads\/2024\/05\/24044916\/laravel-mvc.jpg 768w, https:\/\/assets.bacancytechnology.com\/qanda\/wp-content\/uploads\/2024\/05\/24044916\/laravel-mvc-300x201.jpg 300w\" sizes=\"(max-width: 768px) 100vw, 768px\" \/><\/p>\n<h3>Controller:<\/h3>\n<p>The controller contains logic that updates the model and\/or view in response to input from the users of the app.<\/p>\n<p>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.<\/p>\n<p>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.<\/p>\n<p><strong>Artisan command to create a controller<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\nphp artisan make: controller ShoppingController\r\n<\/pre>\n<p><strong>OR<\/p>\n<p>Resource controller with the default method for CRUD operation<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\nphp artisan make: controller PhotoController --resource\r\n<\/pre>\n<p><strong>Specify the resource model as well<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\nphp artisan make: controller PhotoController --model=Photo --resource\r\n<\/pre>\n<p><strong>Form Request<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\nphp artisan make: controller PhotoController --model=Photo --resource --requests\r\n<\/pre>\n<p>Let\u2019s take a look at an example of a basic controller. Controllers have any number of public methods that will respond to incoming requests.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\n<?php\r\nnamespace App\\Http\\Controllers;\r\nuse App\\Models\\User;\r\nuse Illuminate\\View\\View;\r\nclass UserController extends Controller\r\n{\r\n   \/**\r\n    * Show the profile for a given user.\r\n    *\/\r\n   public function show(string $id): View\r\n   {\r\n       return view('user.profile', [\r\n           'user' => User::findOrFail($id)\r\n       ]);\r\n   }\r\n}\r\n<\/pre>\n<p><strong>Define the route for a particular controller<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\nuse App\\Http\\Controllers\\UserController;\r\nRoute::get('\/user\/{id}', [UserController::class, 'show']);\r\n\r\n\/\/ Resource controller\r\nRoute::resource('users', UserController::class);\r\n<\/pre>\n<p><strong>Partial Resource Route<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\nRoute::resource('photos', PhotoController::class)->only([\r\n   'index', 'show'\r\n]);\r\n<\/pre>\n<p><strong>Naming routes<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\nRoute::resource('photos', PhotoController::class)->names([\r\n   'create' => 'photos.build'\r\n]);\r\n<\/pre>\n<p><strong>API Resource route<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\nRoute::apiResource('photos', PhotoController::class);\r\n<\/pre>\n<p><strong>Define middleware for the controller<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\nRoute::get('profile', [UserController::class, 'show'])->middleware('auth');\r\n<\/pre>\n<p><strong>OR<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\nclass UserController extends Controller\r\n{\r\n   \/**\r\n    * Instantiate a new controller instance.\r\n    *\/\r\n   public function __construct()\r\n   {\r\n       $this->middleware('auth');\r\n       $this->middleware('log')->only('index');\r\n       $this->middleware('subscribed')->except('store');\r\n   }\r\n}\r\n<\/pre>\n<p><strong>You can call the existing controller\u2019s method within the controller<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\n $this->MyCustomFunction();\r\n<\/pre>\n<p><strong>Dependency Injection in the controller\u2019s method<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\n<?php\r\nnamespace App\\Http\\Controllers;\r\nuse App\\Repositories\\UserRepository;\r\nclass UserController extends Controller\r\n{\r\n   \/**\r\n    * Create a new controller instance.\r\n    *\/\r\n   public function __construct(\r\n       protected UserRepository $users,\r\n   ) {}\r\n}?>\r\n<\/pre>\n<p><strong>Method injection<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\n<?php\r\nnamespace App\\Http\\Controllers;\r\nuse Illuminate\\Http\\RedirectResponse;\r\nuse Illuminate\\Http\\Request;\r\nclass UserController extends Controller\r\n{\r\n   \/**\r\n    * Store a new user.\r\n    *\/\r\n   public function store(Request $request): RedirectResponse\r\n   {\r\n       $name = $request->name;\r\n       \/\/ Store the user...\r\n       return redirect('\/users');\r\n   }\r\n}\r\n<\/pre>\n<h3>Model:<\/h3>\n<p>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\u2019s request because the controller can\u2019t interact with the database by itself. The model interacts with the database and returns the required data to the controller.<\/p>\n<p>Laravel includes Eloquent, an object-relational mapper (ORM) that makes it enjoyable to interact with your database.<\/p>\n<p>To get started, let\u2019s create one model that is basically by default stored in app\/Models.<\/p>\n<p><strong>Generate new model<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\nphp artisan make: model Flight\r\n<\/pre>\n<p><strong>You can create migration files as well<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\nphp artisan make: model Flight --migration\r\n<\/pre>\n<p><strong>Other types of classes that you can create<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\n# Generate a model and a FlightFactory class...\r\nphp artisan make: model Flight --factory\r\nphp artisan make: model Flight -f\r\n# Generate a model and a FlightSeeder class...\r\nphp artisan make: model Flight --seed\r\nphp artisan make: model Flight -s\r\n# Generate a model and a FlightController class...\r\nphp artisan make: model Flight --controller\r\nphp artisan make:model Flight -c\r\n# Generate a model, FlightController resource class, and form request classes...\r\nphp artisan make: model Flight --controller --resource --requests\r\nphp artisan make: model Flight -crR\r\n# Generate a model and a FlightPolicy class...\r\nphp artisan make: model Flight --policy\r\n# Generate a model and a migration, factory, seeder, and controller...\r\nphp artisan make: model Flight -mfsc\r\n# Shortcut to generate a model, migration, factory, seeder, policy, controller, and form requests...\r\nphp artisan make: model Flight --all\r\n# Generate a pivot model...\r\nphp artisan make: model Member --pivot\r\nphp artisan make: model Member -p\r\n<\/pre>\n<p><strong>You can easily inspect the model by<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\nphp artisan model: show Flight\r\n<\/pre>\n<p><strong>The basic structure of the model<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\n<?php\r\nnamespace App\\Models;\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\nclass Flight extends Model\r\n{\r\n   \/\/ ...\r\n}\r\n?>\r\n<\/pre>\n<p><strong><br \/>\nYou can define various variables for model <\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\n<?php\r\nnamespace App\\Models;\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\nclass Flight extends Model\r\n{\r\n   \/**\r\n    * The table associated with the model.\r\n    *\r\n    * @var string\r\n    *\/\r\n   protected $table = 'my_flights';\r\n   protected $primaryKey = 'my_flight_id';\r\n   public $incrementing = 'false';\r\n   protected $keyType = 'string';\r\n   public $timestamps = false;\r\n   protected $dateFormat = 'U';\r\n   const CREATED_AT = 'creation_date';\r\n   const UPDATED_AT = 'updated_date';\r\n   protected $connection = 'sqlite';\r\n   protected $fillable = ['name'];\r\n   protected $guarded = [];\r\n\r\n}\r\n?>\r\n<\/pre>\n<p><strong>Create unique UUID<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\nuse Illuminate\\Database\\Eloquent\\Concerns\\HasUuids;\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\nclass Article extends Model\r\n{\r\n   use HasUuids;\r\n   \/\/ ...\r\n}\r\n$article = Article::create(['title' => 'Traveling to Europe']);\r\n$article->id; \/\/ \"8f8e8478-9035-4d23-b9a7-62f4d2612ce5\"\r\n<\/pre>\n<p><strong>Retrieving model<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\nuse App\\Models\\Flight;\r\nforeach (Flight::all() as $flight) {\r\n   echo $flight->name;\r\n}\r\n<\/pre>\n<p><strong>Building Query<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\n$flights = Flight::where('active', 1)\r\n              ->orderBy('name')\r\n              ->take(10)\r\n              ->get();\r\n<\/pre>\n<p><strong>Fresh\/Refreshing Model<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\n$flight = Flight::where('number', 'FR 900')->first();\r\n$freshFlight = $flight->fresh(); \/\/ will not effect $flight\r\n$flight = Flight::where('number', 'FR 900')->first();\r\n$flight->number = 'FR 456';\r\n$flight->refresh();\r\n$flight->number; \/\/ \"FR 900\"\r\n<\/pre>\n<p><strong>Chunking Result<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\nuse App\\Models\\Flight;\r\nuse Illuminate\\Database\\Eloquent\\Collection;\r\nFlight::chunk(200, function (Collection $flights) {\r\n   foreach ($flights as $flight) {\r\n       \/\/ ...\r\n   }\r\n});\r\n<\/pre>\n<p><strong>Not found exception<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\n$flight = Flight::findOrFail(1);\r\n$flight = Flight::where('legs', '>', 3)->firstOrFail();\r\n<\/pre>\n<p><strong>Mass Assignment<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\nuse App\\Models\\Flight;\r\n$flight = Flight::create([\r\n   'name' => 'London to Paris',\r\n]);\r\n<\/pre>\n<p><strong>Insert<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\n$flight = Flight::create([\r\n   'name' => 'London to Paris',\r\n]);\r\n<\/pre>\n<p><strong>Update<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\nuse App\\Models\\Flight;\r\n$flight = Flight::find(1);\r\n$flight->name = 'Paris to London';\r\n$flight->save();\r\n<\/pre>\n<p><strong>Delete Model<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\nuse App\\Models\\Flight;\r\n$flight = Flight::find(1);\r\n$flight->delete();\r\n<\/pre>\n<p><strong>Soft Delete Model<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\n<?php\r\nnamespace App\\Models;\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\nuse Illuminate\\Database\\Eloquent\\SoftDeletes;\r\nclass Flight extends Model\r\n{\r\n   use SoftDeletes;\r\n}\r\n$flight->restore(); \/\/ The restore method will set the model's deleted_at column to null:\r\n$flight->forceDelete(); \/\/ Permanently Delete model\r\n?>\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>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&#8217;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 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":10379,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[10],"tags":[],"class_list":["post-10385","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-laravel"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/10385"}],"collection":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/comments?post=10385"}],"version-history":[{"count":5,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/10385\/revisions"}],"predecessor-version":[{"id":10391,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/10385\/revisions\/10391"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media\/10379"}],"wp:attachment":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media?parent=10385"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/categories?post=10385"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/tags?post=10385"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}