Creating custom class on Laravel is easy to apply. Often we need additional classes to summarize and facilitate us in building applications.
Laravel is a PHP framework that implements a fairly robust MVC concept and a fairly viscous application of Object Oriented Programming. In addition, Laravel has a fairly neat encoding structure that makes the new custom class on Laravel applications to be fast and easy. Follow this short tutorial
Immediately, we begin to create a custom class laravel that will be used to store data in a database table.
Table of Contents
How to Create a Custom Class Laravel 5.5 for beginners
1. Add a new folder inside the app folder on the Laravel project folder that we created. For example, I created a folder named CustomClass
2. Add a new file in the CustomClass folder with the name record_log.php
3. Fill in the following class code in the record_log.php file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <?php namespace App\CustomClass; use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; use Illuminate\Support\Facades\Hash; use App\t_log; use App\User; class record_log { public static function save_log($token, $ket_log, $post_log) { try{ $getuser = User::where('api_token', $token)->first(); if(!$getuser){ $id = 0; }else{ $id = $getuser->id_user; } try { $data = t_log::create([ 'id_user'=> $id, 'ket_log'=> $ket_log, 'post_log'=> $post_log, ]); } catch (\Illuminate\Database\QueryException $ex) { //dd ($ex->getMessage()); } } catch(\Illuminate\Database\QueryException $ex){ //dd ($ex->getMessage()); } } } |
A brief description
The above class is used to store user logs in a database every time a user performs an activity on an application system.
Don’t forget to record the namespace
1 | namespace App\CustomClass; |
4. To access the class as follows
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; use Illuminate\Support\Facades\Hash; use App\User; use App\CustomClass\record_log; class loginController extends Controller { public function login(Request $request) { ....................... record_log::save_log($api_token,'access login',json_encode($request->all())); ....................... } } |
Done, hopefully, the above tutorial can help you, beginners, to learn Laravel.
Maybe you are interested to read the article Restful API Tutorial With Lumen Laravel 5.5 For Beginners
Leave a Reply