top of page
Search

Create ContactController

  • Nov 7, 2022
  • 4 min read

Updated: Dec 14, 2022

Controllers assemble related request handling logic into a single class, ContactController class handles all incoming requests related to contacts, including storing, showing, updating, and deleting contacts. By default, controllers are stored in the app/Http/Controllers directory.

I have used resource controller. It means Laravel resource routing assigned the typical CRUD routes to the ContactController.

make: controller - Artisan command, --resource or -r options – to generate resource controller

php artisan make:controller ContactController -r

I have used above command to generate ContactController.

php artisan route:list

This way we can check actions handled by resource ContactController.


ree

Inside the ContactController, I have imported the below classes.

use Illuminate\Http\Request class provide an object-oriented approach to communicate with current HTTP request, it retrieve the input, cookies and files that were carry by request.

use Illuminate\Support\Facades\Auth class will check the incoming HTTP request if it is authenticated return true other wise redirect the user to login page.

use Illuminate\Support\Facades\File class exends the PHP SplFileInfo class and offer several methods for interacting with the file


Protecting Routes

Route middleware only allow authenticated user to access a given route. In Laravel the auth middleware defined at Illuminate\Auth\Middleware\Authenticate. also the middleware is registered in HTTP kernel; therefore, Inside controller's constructor, I have attached the middleware and passed an array to make sure authenticated user with verified email can access the routes.


public function __construct() { $this->middleware(['auth', 'verified']); }


Index Method

I have retrieved all records and passed them into $contacts variable, and through compact () method passed all the data to view. In Laravel, you can use compact () method to pass an array of the variables from controller to view.


public function index() { $contacts = Contact::all(); return view('home', compact('contacts')); }


Create Method

I have just returned create view.


public function create() { return view('create'); }


Validation: Laravel provides several different approaches to validate incoming HTTP requests, the validate method has been provided by the Illuminate\Http\Request object. we can use the validation in differently way either inside the controller's method or create a FormRequest class to validate the incoming requests. If validation fails then Illuminate\Validation\ValidationException exception throws an error message. Here i have applied the validation rules inside the controllers method.


Authorization: Laravel provides an easy way to authorize user action. Through authorization we can limit even authenticated users access. There are two main ways of authorizing actions, gates and policies. Here in ContactController, I have authorized user action directly within the methods without using policy.


Stored Method

To store new contact into the contacts table:

- I created $request variable.

- For name and mobile fields, I have set validation rule required and, for photo field, I have validated the mime type of file to make sure the user is only able to upload specific file types.

- I created $contacts variable and set input request for each field.

- I created $fileName as a variable and passed file request on it. As GetClientOriginalName() method is considered unsafe and it is possible for malicious users to detect it, I have used hashName() method to get file name including current time and an extension for the given file upload.

- I defined the storage path. I have asked upload orphan image in public/storage/media, I have used storeAs () method. In this way, I will have more control and filename will not be automatically assigned to the stored file. There is another method putFileAs which has similar functionality.

- I have authorized the action of authenticate user - $contacts->user_id = Auth::user()->id; This way ensures only authenticated users whose id matches contact user_id can store the record.

- I saved new record.

- And I returned with success message.

-


public function store(Request $request) { $this->validate($request, [ 'name' => 'required|regex:/^[\pL\s\-]+$/u', 'mobile' => 'required|numeric|digits:11', 'photo' => 'required|mimes:jpeg,bmp,png,jpg', ]); $contacts = new Contact; $contacts->name = $request->input('name'); $contacts->mobile = $request->input('mobile'); //GetClientOriginalName() method is considered unsafe //and it is possible for malicious users to detect it $fileName = time().$request->file('photo')->hashName(); $path = $request->file('photo')->storeAs('media', $fileName, 'public'); $contacts['photo'] = '/storage/'.$path; $contacts->user_id = Auth::user()->id; $contacts->save(); return back()->with('success', 'Contact created successfully'); }


The Public Disk

The public disk is part of application's filesystems configuration file and it is publicly accessible. the public disk by default use the local driver and stores its file in Storage/app/public/media. however; to make the files accessible from browser need to create a symbolic link from public/storage to storage/app/public/media.


To create the symbolic link, in terminal run the following command: php artisan storage:link


dd () method

dd () is stand for Dump and Dies, this method dumps and end execution of the script, i have used this method for debugging purpose.


Show Method

- I have set WHERE condition base on record id to retrieve specific contact.

- Also I used WHERE condition to authorize only authenticate user, whose id = contact user_id

- I used the firstOrFail() method, it will abort if no record is found in query.

- I passed the query to delete view by compact () method.


public function show($id) { $contacts = Contact::where('id', $id)->where('user_id', Auth::user()->id)->firstOrFail(); return view('delete', compact('contacts')); }


Edit Method

- I have set WHERE condition base on record id to retrieve specific contact.

- Also I used WHERE condition to authorize only authenticate user, whose id = contact user_id.

- I used the firstOrFail() method. It will abort if no record found in query.

- I passed the query to edit view by compact () method.


public function edit($id) { $contacts = Contact::where('id', $id)->where('user_id', Auth::user()->id)->firstOrFail(); return view('edit', compact('contacts')); }


Update Method

- I set validation for name and mobile fields.

- I set input request for name and mobile fields.

- For photo field, I have set if () condition. If request contains file, in this case first delete file from storage and then update.

- I also set authorization for user.

- I saved new changes.

- Then I returned with success message.


public function update(Request $request, $id) { $this->validate($request, [ 'name' => 'required|regex:/^[\pL\s\-]+$/u', 'mobile' => 'required|numeric|digits:11', 'photo' => 'mimes:jpeg,bmp,png,jpg', ]);

$contacts = Contact::findOrFail($id); $contacts->name = $request->input('name'); $contacts->mobile = $request->input('mobile'); if($request->hasfile('photo')){ $path=public_path($contacts->photo); if(File::exists($path)){ File::delete($path); } $fileName = time().$request->file('photo')->hashName(); $path = $request->file('photo')->storeAs('media', $fileName, 'public'); $contacts ['photo'] = '/storage/'.$path; } $contacts->user_id = Auth::user()->id; $contacts->save(); return back()->with('success', 'Contact updated successfully'); }

Destroy Method

- I have set WHERE condition base on record id to retrieve specific contact.

- Also I used WHERE condition to authorize only authenticate user, whose id = contact user_id

- I used the firstOrFail() method, it will abort if no record found in query.

- Then I first deleted photo (orphan) from storage.

- After that I deleted the record from database.

- Lastly I returned to user dashboard and display success message.


public function destroy($id) { $contacts = Contact::where('id', $id)->where('user_id', Auth::user()->id)->firstOrFail(); unlink(public_path($contacts->photo)); $contacts->delete(); return redirect()->route('user.index')->with('success', 'Item deleted successfully'); }

Orphan Images Short Demo


 
 
 

Recent Posts

See All
Project Introduction

In this Project, I am looking to develop a Laravel web application for contact list and host it on a public web server. The project has...

 
 
 

Comments


Thanks for submitting!

© 2023 by DO IT YOURSELF. Proudly created with Wix.com

bottom of page