Skip to main content

Posts

Showing posts with the label Laravel

Laravel Tip and Tricks

1. Database Connection 2. Authentication 1. Database connection Using DB class import class use Illuminate\Support\Facades\DB; Access Database Name -dump(\DB::connection()->getDatabaseName()); Access Database Connection Name through which the project is connected to the DB -dump(DB::connection()->getName()); Access in blade file/view| -{{\DB::getDatabaseName();}} 2. Authentication Get Current Auth user details import class use Auth; -dd(Auth::user)

Relational queries in laravel

 1. Suppose you want to query parent model and also apply condition on child relation model and you also want to get specifies data, not all data from child table in hasMany relationship. $collection_products = Product::on('business');             // query()             if($selectedColor != null){                 $collection_products = $collection_products->with(['variants' => function($query) use ($selectedColor){                 $query->where('color','=',$selectedColor);             }]);             $collection_products = $collection_products->whereHas('variants',function(Builder $query) use ($selectedColor){                 $query->where('color','=',$selectedColor);             });     ...

Mostly use of collection methods in laravel

Example code here. <? php namespace App \ Http \ Controllers ; use Illuminate \ Http \ Request ; use Illuminate \ Support \ Str ; class CollectionController extends Controller {     const PROJECT_TYPES = [         'action' ,         'base resource' ,         'A W S' ,         'lara beans'     ];     const MOVIES_TYPES = [         [ 'id' => 1 , 'name' => 'action' ],         [ 'id' => 2 , 'name' => 'base resource' ],         [ 'id' => 3 , 'name' => 'A W S' ],         [ 'id' => 4 , 'name' => 'lara beans' ]     ];     function mapWithSlugs () {         dump ( 'Convert name of arrays into slug using Slug function and iterate array with map function' );         $slugs = [];         foreac...

Helper function | custom helper function in laravel

 Helper function can be implement both with pure functions and by class based functions. Helper function can be access anywhere in your app, Event they are autoload as well via composer on every user request. e.g dd() data dump is an common heler function that we use while debugginh in laravel. How to implement helper functions 1 . Make a directory in app folder with  helpers name. Create a file helper.php Write dummy code in this file <? php function message ( string $string = '' ) {     return 'Hello' ; } ?> 2. Now register/set the path of this file in composer.json file add the path in autoload object like that. I define a files key and assign array to it.Array contains all helper function files path with comma separation. "autoload" : {     "psr-4" : {         "App \\ " : "app/"     },     "files" : [ "app/helpers/helper.php" ],     "classmap" : [         "database/see...

Facades in laravel

Facades provide static like interface to services inside the service container. we can access underlying implementation on these services (methods and properties). we can access every method in service classes without creating their instance(object). Mean it automatically resolve dependencies by creating instance of the service classes. How facades work ? 1) The service class contain only one method 'getFacadeAccessor()'. 2 ) This class also extend facades base class 3) So when we call method of this class without instance like cache::get('name) 4) It automatically call getFacadeAccessor() method create instance than find the method of the service class. How do I create a facade class and use in my application ? Since laravel largely uses facades rather every non static function has its equivalent facade available in service container, we must also follow the same way in our custom application. All of Laravel’s facades are defined in the Illuminate\Support\Facades namespace...

Change public url to domain url in production mode for laravel project

 Reference links 1. https://stackoverflow.com/questions/28364496/laravel-5-remove-public-from-url/54275198#54275198 2. https://devops.ionos.com/tutorials/how-to-set-up-ip-and-port-based-virtual-hosting-vhosts-with-apache-web-server-on-centos-7.html 3. help full video  https://www.youtube.com/watch?v=XZAF5yR-WYQ step 1 Go to  cd /etc/httpd/conf vim httpd add  ip entry your-ip:80 :wq save n close step 2 Go to cd /etc/httpd/conf.d vim bsms.conf wrote host entry as shown in video Step 3 add host entru with domain ip in hosts file vim /etc/hosts your-ip <space> domain.com Step 4 Restart the httpd systemctl restart httpd  

learning resources and channals

 For Laravel Channal Name : A ndrew Schmelyun Link: https://www.youtube.com/@aschmelyun 10 useful websites for web developement https://www.youtube.com/watch?v=uhNLY5y9-Kg&list=PL_ZUs2eBjBisBYhqBmy7aDuBSl6mjxCdr&index=7  React Native Bug Ninza : It is a youtube channal.

Two ways setup foreign key constained in migration

 

Define group routes and apply middleware on routes

 In ths article we will se how to define group route, also apply "middleware" on it. Define "prefix" and route "name" as well Route :: group ([ 'middleware' => [ 'auth' , 'verified' ], 'prefix' => 'tags' , 'as' => 'tags.' ], function () {     Route :: get ( '/' ,\App\Http\Livewire\Tuts\ Tag :: class )-> name ( 'index' );     // so route name will be like so tags.index });

Laravel Case Sensitive Query Search Example

       Sometime we have records in users table with following name like "Adnan", "ADNAN" and "adnan". now you just need to get case sensitive name like if you search "Adnan" then it should only get that record. so that solution i will give you simple example and show you how to make case sensitive query using mysql BINARY in laravel. you can use this example in laravel 6, laravel 7, laravel 8 and laravel 9 version. $users = User :: select ( "id" , "name" , "email" ) -> where ( DB :: raw ( 'BINARY `name`' ), "Adnan" ) -> get ();

What is the use of bootstrap folder in laravel ?

 This folder don't have concern with bootstrap framework. This folder belongs to laravel framework. First, understand the meaning of the term "Bootstrapping". It is the process of self start processing in the framework or in any system. These file automatically load the classes ans start out project. Let's understand which classes automatically load up, run, and boot up. Service Container, Facades, Middleware, Service Provider and Kernal. these are dependencies are set up so that laravel fulfill your request to the application.

Touch Many-to-Many Parent and sync methods in laravel

  Touch method 1) Most of the time user update data in the child table but also wants to update the user (parent) table updated_at field. For that, you don't need to update it manually by querying it. Use the touch method on the model object inside controller. This method will only update the updated_at field to the current date/time. $user -> touch (); 2) You could also update field automatically, lets say where there is new comment on post and you also want to update post table updated_at feild at the same time than what you need to do Inside Comment Model define belongtomany relationship to post model class and also specify a protected variable protected $touches = [ 'post' ]; //post is realtional method Sync() Method This method is use to add multiple id's of data into pivot table with many to many relationship. This method remove existing id's and add new id's. If you want existing id's remian in the pivot table than you will use this code. $book ...

Collection methods examples in laravel

 Collection Method use to modfy the data or get data in our required format <?php namespace App\Http\Controllers ; use Illuminate\Http\ Request ; use Illuminate\Support\ Str ; class CollectionController extends Controller {     const PROJECT_TYPES = [         'action' ,         'base resource' ,         'A W S' ,         'lara beans'     ];     const MOVIES_TYPES = [         [ 'id' => 1 , 'name' => 'action' ],         [ 'id' => 2 , 'name' => 'base resource' ],         [ 'id' => 3 , 'name' => 'A W S' ],         [ 'id' => 4 , 'name' => 'lara beans' ]     ];     function mapWithSlugs () {         dump ( 'Convert name of arrays into slug using Slug function and iterate array with map function' );        ...

Guards, Gates and Policies code logic

  Guards Gates Gates are closure based means it can be access from throughout of our application. We define our Gates inside AuthserviceProvider under boot method. We can define many gates as we needed. we define gate for both roles and permissions. Now use Gate inside controller method, where you want to authorize user action. Policies In the policies, we map policy class to the specific model (Eluquant model). With the help of command we create policyClass like so. php artisan make:policy PostPolicy --model=Post  Define policy in the controller for a particular action. Define policy check  inside policy class view method. here we are checking is user_id is equal to the post user_id if check success  than it will return true and user can do this task. Authorization function in laravel But Laravel enables us to write policy to manage every policy check instead if writing checks in each method. For that, we will use laravel Authorize function. let make it make copy of...