class MyCustomClassName { public function __construct() { } public function whatever_whatever(){ // Code goes here. And can use anything from the construct. The construct will always load first } }
A Controller or Class in MVC are both just classes.
So… Technically speaking.
It is possible to write all your functionality inside your controllers and completely ditch the classes folder.
But! The purpose of breaking out into separate classes is re-usability.
Controllers :
<?php namespace App\Http\Controllers; class MyCustomController extends Controller { }
Classes :
<?php namespace App\Classes\MyCustomClass; class ClassNameWhateverWhatever { }
Why Classes, what is the point?
—————————————————————–
Classes serve as containers for specific purposes.
For example.
You create a class for :
Car
—
And inside your class you write all your functionality.
A car can have specific functionality.
—
moveForward()
reverse()
brake()
switchOnLights()
—————————————————————–
Then, you reference your car class inside your contollers.
—
So something like
car->moveForward();
This design strategy makes your code extremely easy to re-use without having to re-write additional functionality. This is why we seperate everything into a class and then we create another class called a controller class and reference our classes inside the controller classes.
Save Function (Update and Add in 1 function based on ID)
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\DB; use Illuminate\Http\Request; class RandomController extends WhateverWhateverController { public function saveTermsAndConditions(Request $request){ if (isset($request->id)) { // Update try { DB::table('table_name')->where('id',$request->id)->update( array( 'field'=>$request->field, 'content'=>$request->content, 'updated_at' => date("Y-m-d H:i:s", strtotime('now')), ) ); $termsAndConditions = DB::table('table_name')->where('id', $request->id)->first(); } catch (\Exception $e) { return response()->json($e); } } else { // Add try { $id = DB::table('table_name')->insertGetId( array( 'field' => $request->field, 'content' => $request->content, 'created_at' => date("Y-m-d H:i:s", strtotime('now')), 'updated_at' => date("Y-m-d H:i:s", strtotime('now')) ) ); $termsAndConditions = DB::table('table_name')->where('id', $id)->first(); } catch (\Exception $e) { return response()->json($e); } } return $termsAndConditions; } }
Required Laravel includes
use Illuminate\Support\Facades\DB; use Illuminate\Http\Request;
Select Query
class MySpecialController extends Controller { public function rawQueryFunctionNameSelect(Request $request){ $rawQuery= DB::select( DB::raw( 'SELECT * FROM table_name' ) ); return $rawQuery; } }
Update Query
class MySpecialController extends Controller { public function rawQueryFunctionNameUpdate(Request $request){ DB::table('table_name')->where('id',$request->id)->update( array( 'field'=>$request->field, 'content'=>$request->content, ) ); } }