Company Controller

Laravel use Model View Controller (MVC). We already look at Model, now are looking at Controller. A controller is responsible for responding to the user input and perform interactions on the data model objects. Controllers lives in the App->Http->Controllers

If we flag --resource, it will bootstrap CRUD (Create, Read, Update, Delete) functions to newly created controller

php artisan make:controller CompanyController --resource

We used auth middleware to protect the controller functions by putting in the controller constructor, allowing only authenticated users.

$this->middleware('auth');

Even though a user is authenticated but the below code protects the user from accessing the function unless the log-in user has read permission (authorization) on Company Model.

$this->authorize('read', Company::class);

In the below code, we build a database query provided by Laravel. In the DB facade, we use a table name (countries) and it joins the table companies on counties.id equals to companies.country_id. Below query only return non-deleted (soft delete) records by providing not null where clause on 'deleted_at'. The query paginates 20 records on each page. We will look at how we can do that later in the tutorial.

$companies =DB::table('countries') ->join('companies','countries.id', '=', 'companies.country_id') ->whereNull('deleted_at') ->select(['countries.name as country_name', 'companies.deleted_at','companies.id', 'companies.name', 'companies.telephone', 'companies.emailAddress']) ->paginate(20);

To create session variable we use session(['name' => 'value']). This session variables are used to display icon on view using font-awesome later in tutorial.

session(['pageTitle' => 'Companies']); session(['pageTitleIcon' => 'fa fa-th-list']);

To get all records of model/table, we use Model::all()

$countries = Country::all();

To return the value(s) from a controller to its view, we use the below code. In this code, we are passing two variables, companies and countries.

return view('companies.index', [ 'companies' => $companies, 'countries' => $countries, ]);

In the view form, there are three submit button; save, save & close and save & new. Each of them has a different value, 1,2,3

$action = $request->input('btn-submit');

It is a must to have validation on the user input form before we save it to the database. Below is an example where we validate. For the country id field, it is required and not value equals 0 (--select-- option), name is required, unique in company table and name field and max length 255 characters, address line 1 is required and max length 255 characters, address line can be nullable and max length 255 characters. For example, the email address is required, unique, email, and max length 255 characters.

$this->validate($request, [ 'country_id'=> 'required|not_in:0', 'name' => 'required|unique:companies,name|max:255', 'addressLine1'=> 'required|max:255', 'addressLine2'=> 'nullable|max:255', 'city'=> 'nullable|max:255', 'telephone'=> 'required|unique:companies,telephone|max:255', 'fax'=> 'nullable|max:255', 'emailAddress'=> 'required|unique:companies,emailAddress|email|max:255' ]);

Below is an example we insert data into the database with the help of Laravel, Model::create(fields). In this statement we are passing name, address line 1, address line 2, city, country id, telephone, fax, email address. Since we need to capture id of the record created, it tail with ->id

$id = Company::create($request->only(['name','addressLine1','addressLine2','city','country_id','telephone', 'fax','emailAddress']))->id;

In the resources->lang create a PHP file called message.php, where we store all messages. Replace the file content with the following code.

<?php return [ 'add_success' => 'Record create successful', 'update_success' => 'Record update succesful', 'delete_success' => 'Record delete successful', 'record_exist' => 'Record already exist on database', 'no_item_selected' => 'Please select a item', 'record_restore' => 'Record restore successful', 'update_password_success'=> 'Password save successful', 'system_error'=> 'System error, please contact your system administrator', 'EntitlementNotDefine' =>'Please contact your system administrator, leave entitlement not defined', 'NoWorkingDayDefine' => 'Working Days are not define', 'NotEnoughEntitlement' => 'Not enough entitlement', 'ApplicationTotalDeductLessThanZero' => 'Technical problem, please contact your system administrator', 'ApplicationOfThisRunningYear' => 'The application should be for this running year.Cycle month is ', ];

It will redirect to companies route with success session variable and value of "add_sucess".

return redirect()->route('companies')->with('success', trans('message.add_success'));

To get record by its primary key on a given table, we used Model::find(primary_key)

$company = Company::find($id);

Another way of providing fields to create/update statement, we can use $request->all() that matches all form fields to model/database fields

$company->update($request->all());

In order to delete a record, we first need to find the record using Model::find(id), then we can simply use company->delete(); Since we are planning to use AJAX call to the method, we return an AJAX response.

$company = Company::find($request->id); $company->delete(); return response()->json($company);

In the view, we are going to allow users to perform multi-action on selected (checked) records, for example, delete multiple records at once. $ids = $request->id; capture all selected primary keys (id) of records. We then pass it to destroy function as shown below to soft delete them from the database.

Company::destroy($ids);

Besides soft delete, we also need to restore those records to be active. Below is an example, where we query to reterive them and make them active records.

Company::onlyTrashed() ->whereIn('id', $ids) ->restore();

In the search function, we check if a user requested all companies or a company and active or trash/deleted record. Based on them, we use if-else logic to get the data from the database.

Controller full code

Note: Please use the copy button to copy the source code.

We need to include the following import statement(s)
use App\Models\Company;
use App\Models\Country;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;

class CompanyController extends Controller { public function __construct() { $this->middleware('auth'); } public function index() { $this->authorize('read', Company::class); $companies =DB::table('countries') ->join('companies','countries.id', '=', 'companies.country_id') ->whereNull('deleted_at') ->select(['countries.name as country_name', 'companies.deleted_at','companies.id', 'companies.name', 'companies.telephone', 'companies.emailAddress']) ->paginate(20); session(['pageTitle' => 'Companies']); session(['pageTitleIcon' => 'fa fa-th-list']); $countries = Country::all(); return view('companies.index', [ 'companies' => $companies, 'countries' => $countries, ]); } public function create() { $this->authorize('create', Company::class); session(['pageTitle' => 'Companies: New']); session(['pageTitleIcon' => 'fa fa-pencil']); $countries = Country::all(); return view('companies.create', [ 'countries' => $countries, ]); } public function store(Request $request){ $this->authorize('create', Company::class); $action = $request->input('btn-submit'); $this->validate($request, [ 'country_id'=> 'required|not_in:0', 'name' => 'required|unique:companies,name|max:255', 'addressLine1'=> 'required|max:255', 'addressLine2'=> 'nullable|max:255', 'city'=> 'nullable|max:255', 'telephone'=> 'required|unique:companies,telephone|max:255', 'fax'=> 'nullable|max:255', 'emailAddress'=> 'required|unique:companies,emailAddress|email|max:255' ]); $id = Company::create($request->only(['name','addressLine1','addressLine2','city','country_id','telephone', 'fax','emailAddress']))->id; switch($action){ case 1: $countries = Country::all(); $company = Company::find($id); return view('companies.show', [ 'company' => $company, 'countries' => $countries, ])->with('success', trans('message.add_success')); break; case 2: return redirect()->route('companies')->with('success', trans('message.add_success')); break; case 3: return redirect()->route('companies.create')->with('success', trans('message.add_success')); break; } } public function show($id) { $this->authorize('update', Company::class); session(['pageTitle' => 'Companies: Edit']); session(['pageTitleIcon' => 'fa fa-pencil']); $countries = Country::all(); $company = Company::find($id); return view('companies.show', [ 'company' => $company, 'countries' => $countries, ]); } public function update(Request $request, $id) { $this->authorize('update', Company::class); $company = Company::find($id); $company->update($request->all()); $action = $request->input('btn-submit'); switch($action){ case 1: $countries = Country::all(); $company = Company::find($id); return view('companies.show', [ 'company' => $company, 'countries' => $countries, ])->with('success', trans('message.update_success')); break; case 2: return redirect()->route('companies')->with('success', trans('message.update_success')); break; case 3: return redirect()->route('companies.create')->with('success', trans('message.update_success')); break; } } public function destroy(Request $request) { $this->authorize('delete', Company::class); $company = Company::find($request->id); $company->delete(); return response()->json($company); } public function multi_action(Request $request) { $ids = $request->id; $action = $request->input('btn-submit'); if($ids != null) { switch($action){ case 1: $this->authorize('delete', Company::class); Company::destroy($ids); return redirect()->route('companies')->with('success', trans('message.delete_success')); break; case 2: $this->authorize('restore', Company::class); Company::onlyTrashed() ->whereIn('id', $ids) ->restore(); return redirect()->route('companies')->with('success', trans('message.record_restore')); break; } } else{ return redirect()->route('companies')->with('success', trans('message.no_item_selected')); } } public function search(Request $request){ $this->authorize('read', Company::class); $country_id = $request->country_id; $status = $request->status; $companies; if($status == 1) //active { if($country_id > 0){ $companies =DB::table('countries') ->join('companies','countries.id', '=', 'companies.country_id') ->whereNull('deleted_at') ->where('companies.country_id', '=', $country_id) ->select(['countries.name as country_name', 'companies.deleted_at','companies.id', 'companies.name', 'companies.telephone', 'companies.emailAddress']) ->paginate(20); } else{ $companies =DB::table('countries') ->join('companies','countries.id', '=', 'companies.country_id') ->whereNull('deleted_at') ->select(['countries.name as country_name', 'companies.deleted_at','companies.id', 'companies.name', 'companies.telephone', 'companies.emailAddress']) ->paginate(20); } } else{ if($country_id > 0){ $companies =DB::table('countries') ->join('companies','countries.id', '=', 'companies.country_id') ->whereNotNull('deleted_at') ->where('companies.country_id', '=', $country_id) ->select(['countries.name as country_name', 'companies.deleted_at','companies.id', 'companies.name', 'companies.telephone', 'companies.emailAddress']) ->paginate(20); } else{ $companies =DB::table('countries') ->join('companies','countries.id', '=', 'companies.country_id') ->whereNotNull('deleted_at') ->select(['countries.name as country_name', 'companies.deleted_at','companies.id', 'companies.name', 'companies.telephone', 'companies.emailAddress']) ->paginate(20); } } $countries = Country::all(); return view('companies.index', [ 'companies' => $companies, 'countries' => $countries, ]); } }