Skip to main content

Laravel Framework

laravel 5 Tips

Cache the model

#  Cache the model data using tags (tags are not used when cache is file cache or session cache)
$cacheKey = str_replace(['\\'], [''], __METHOD__) . '(' . $link . ',' . $action . ')';
$response = Cache::tags('admins')->remember($cacheKey, 60, function() use($link, $action) {
    if (!empty($link) && !empty($action) && in_array($action, $this->permissions())) {
        return $result = DB::table('user_links')
            ->where('user_id', '=', Auth::user()->id)
            ->where('link_id', $link)
            ->pluck($action);
    }
    return false;
});
return $response; 


========================================================================= 

Clear Cache

Clear/Flush the cache 
Cache::tags('admins')->flush();

========================================================================= 

Access module specific varable in config

# access module specific varable in config
echo "conmg....".Config::get('admin.variableName');


 
=========================================================================

Execute last query

#execute last query
 \DB::enableQueryLog();     
print_r(\DB::getQueryLog());


OR

$query = MyModel::with('User', 'Car')->orderBy('id', 'desc'); 
echo $query->getQuery()->toSql();
=========================================================================

Asset path

# laravel 5 to get modularize asset path use bellow code 
\Module::asset('admin:');
OR
\Pingpong\Modules\Facades\Module::asset('admin:');
 


# get module path
\Pingpong\Modules\Facades\Module::getModulePath('admin');


 
=========================================================================

Form validation using html markup

# form validation using html markup
 {!! Form::text('name', '', ['class'=>'form-control', 'data-msg-required'=>'Please Enter FAQ Category Name', 'data-rule-required'=>'true', 'data-rule-maxlength'=>'2', 'data-msg-maxlength'=>'Max {0} allowed']) !!}


=========================================================================

 Access route parameters

# get route action, uri and other parameters
$route = $request->route();
$uri = $route->getUri();
$action = $request->route()->getAction();


=========================================================================

Cascade delete schema 

 # define cascade delete schema based on following syntax
Schema::create('permission_user', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('permission_id')->unsigned()->index();
$table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
 

=========================================================================

Seeding code for small tables

 # table seeding code for small tables
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon as Carbon;

class UserTypeTableSeeder extends Seeder
{

    public function run()
    {

        DB::statement('SET FOREIGN_KEY_CHECKS=0;');

        DB::table(<table-name>)->truncate();

        //Create admin role, id of 1
        $model = <UserType-Model>;
        $admin = new $model;
        $admin->name = 'Administrator';
        $admin->created_at = Carbon::now();
        $admin->updated_at = Carbon::now();
        $admin->save();

        //id = 2
        $model = <UserType-Model>;
        $user = new $model;
        $user->name = 'User';
        $user->created_at = Carbon::now();
        $user->updated_at = Carbon::now();
        $user->save();

        DB::statement('SET FOREIGN_KEY_CHECKS=1;');
    }
}


=========================================================================

Create association with third table

# To create association with third table in laravel we called it as a pivotal table the schema would be like this based on requirement we can utilize cascade delete option,
            $table->increments('id');
            $table->integer('player_id')->unsigned();
            $table->integer('team_id')->unsigned();
            $table->foreign('player_id')->references('id')->on('players')->onDelete('cascade');
            $table->foreign('team_id')->references('id')->on('teams')->onDelete('cascade');
here player and Team is master table with association or pivotal table woulld be player_team So please every one make a note with the same whenever we create relationship with third table

2> no need to make unnecessart model for third table as we will utilize  that table directly with association and relation ship with master table

3>Define association in master model file like this
Team model has function like  public function player()
  {
    return $this->hasMany('App\Player');
  }

Or player model has function like  public function team()
  {
    return $this->belongsToMany('App\Team');
  }

=========================================================================

Reference Links : -

# Implement the demo application in laravel 5 datatables
https://github.com/yajra/laravel-datatables-demo  


# laravel models
http://laravel.com/docs/4.2/eloquent#inserting-related-models
http://laravel.com/docs/5.0/eloquent#many-to-many-polymorphic-relations

http://laravel.com/docs/5.1/eloquent 

# Nice link for utilizing middleare and trait for ACL
http://heera.it/laravel-5-0-acl-using-middleware#.VdGf5cuVrU4 


# Here is simple example of what php Traits and how to use it.
http://culttt.com/2014/06/25/php-traits/
http://laravel.com/api/5.0/traits.html
 =========================================================================

Use queue in laravel

# Use Queue in laravel

    1). Install redis loader on fedora 20
        $ yum install redis
        $ sudo service redis start

    2). Install supervisor
        $ sudo yum install supervisor
        $ sudo service supervisord start

    3). configure config in laravel
        /var/www/html/projectname/app/config/queue.php
            add 'default' => 'redis'

    4). Below command create a migration script for "failed_jobs" of database
        $ php artisan queue:failed-table       

    5). Run below command in command prompt
        $ php artisan queue:work redis --daemon --queue=videoconversion

    6). Run following in php file
        Queue::push('App\Queue\VideoConversion', ['videoId' => $lastInsertVideoId], 'videoconversion');

    NOTE: First Run work (step 5) and then step 6. Then check in command prompt whether work is running or not.

    7). Clear redis
        $ redis-cli
        $ flushdb
        $ flushall
 

supervisor log configuration
        1). Create ini file for videoconversion queue
            $vi /etc/supervisord.d/videoconversion_queue.ini

            - Add following content in videoconversion_queue.ini

[program:videoconversion_queue]
command=php artisan queue:work redis --daemon --queue=videoconversion --tries=1
 [**NOTE :tries should be 1, it will log in failed_jobs table]
directory=/var/www/html/projectname

 process_name=%(program_name)s_%(process_num)02d
numprocs=4
autostart=true
autorestart=true
stderr_logfile=/var/log/videoconversionqueue.err.log
stdout_logfile=/var/log/videoconversionqueue.out_%(process_num)02d.log

How to work with supervisor
        1). start supervisor
            $ sudo service supervisord start
        2) check using following command
            $ php aux|grep php
                It will show artisan queue command
        3). Now Run the file using browser which contains Queue::push('App\Queue\VideoConversion', ['videoId' => $lastInsertVideoId], 'videoconversion');


==========================================================================

artisan command for migrations

$ php artisan module:migrate-refresh api

$ php artisan module:migrate-refresh --seed api
==========================================================================

no supported encrypter found. the cipher and / or key length are invalid. laravel


ANS >>>

To elaborate on the cause, the default cipher in confing/app.php is "AES-256-CBC" which needs a 32 character string, but the default key is "SomeRandomString," which is only 16 characters.
So, you can either set the cipher to "AES-128-CBC" which only needs 16 characters, or generate a new 32 character string for the key. Entering "php artisan key:generate" is the simplest solution.

$ php artisan key:generate

//OUT PUT
Application key [5Oc6Up08knDHDgz0oV5cC9B2WF2Aew5j] set successfully.

//Add the above generated key to config/app.php file

'key' => env('APP_KEY', '5Oc6Up08knDHDgz0oV5cC9B2WF2Aew5j'),
'cipher' => 'AES-256-CBC',

========================================================================== 

call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Cache\FileStore' does not have a method 'tags'


ANS >>> 
Tags is not supported to file cache and session cache. This option ('driver') defines the cache driver to be used. It may be the name of any driver set in app/config/cache.php. Setting it to null will use the driver you have set as default in app/config/cache.php. Please note that a driver that supports cache tags is required. The default value for this setting is null.


==========================================================================

 You can also run the local project using bellow command,

 $ php artisan serve

# out put
Laravel development server started on http://localhost:8000

  
==========================================================================

Cross check the password field in database in laravel


if(Hash::check($inputs['password'], $user->password)){
     // your check

==========================================================================

Error Code: 1005. Can't create table '…' (errno: 150)


Error Code: 1005 -- there is a wrong primary key reference in your code
usually it's due to a reference FK field not exist. might be you have typo mistake,or check case it should be same, or there's a field-type mismatch. FK-linked fields must match definitions exactly.
Some Known causes may be :
  1. The two key fields type and/or size doesn’t match exactly. For example, if one is INT(10) the key field needs to be INT(10) as well and not INT(11) or TINYINT. You may want to confirm the field size using SHOW CREATE TABLE because Query Browser will sometimes visually show just INTEGER for both INT(10) and INT(11). You should also check that one is not SIGNED and the other is UNSIGNED. They both need to be exactly the same.
  2. One of the key field that you are trying to reference does not have an index and/or is not a primary key. If one of the fields in the relationship is not a primary key, you must create an index for that field.
  3. The foreign key name is a duplicate of an already existing key. Check that the name of your foreign key is unique within your database. Just add a few random characters to the end of your key name to test for this.
  4. One or both of your tables is a MyISAM table. In order to use foreign keys, the tables must both be InnoDB. (Actually, if both tables are MyISAM then you won’t get an error message - it just won’t create the key.) In Query Browser, you can specify the table type.
  5. You have specified a cascade ON DELETE SET NULL, but the relevant key field is set to NOT NULL. You can fix this by either changing your cascade or setting the field to allow NULL values.
  6. Make sure that the Charset and Collate options are the same both at the table level as well as individual field level for the key columns.
  7. You have a default value (ie default=0) on your foreign key column
  8. One of the fields in the relationship is part of a combination (composite) key and does not have it’s own individual index. Even though the field has an index as part of the composite key, you must create a separate index for only that key field in order to use it in a constraint.
  9. You have a syntax error in your ALTER statement or you have mistyped one of the field names in the relationship
  10. The name of your foreign key exceeds the max length of 64 chars.

Reference: - 
http://stackoverflow.com/questions/9018584/error-code-1005-cant-create-table-errno-150 

==========================================================================

Seed Error - Cannot truncate a table referenced in a foreign key constraint (SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table referenced in a foreign key constraint)

 Ans: The above error occurs due to truncate code in seed file. So go to your seed file and replace (DB::table('users')->truncate();)  with following code,


// just disable the foreign key checks before truncating your table and enable it afterwards

DB::statement('SET FOREIGN_KEY_CHECKS = 0'); // disable foreign key constraints

DB::table('users')->truncate();

DB::statement('SET FOREIGN_KEY_CHECKS = 1'); // enable foreign key constraints


==========================================================================

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

Ans: It just simply means that the value from parent column table on child table column tbale you are inserting doesn't exist on parent table. To avoid this error you need to delete the insert value which does not exists in parent table. 
========================================================================== 


 Amazon S3 (Simple Storage Service)


* Amazon s3(Simple Storage Service) - Is know as Simple Storage Service. Is Secure, Safe, Highly Scalable object storage in cloud.

It can used to store and retrieve any amount of data, at any time, from anywhere on the web.

Amazon s3 is a very affordable solution for hosting data on the web since you only pay for the storage and bandwidth you use.

 Companies commonly use the Amazon s3 for backup and storage, application  or media hosting, hosting high-traffic websites, or for software delivery.

You can store the static content in Amazon s3 for faster retrieve and reduces the costs.

 It also allows versioning, so you can have a record of changes and can roll back to any previous version when needed.

Amazon s3 provides standards-based REST and SOAP web services APIs so you can programmatically store, retrieve and manage your data.

 Most developers building application on Amazon s3 use software development kit (SDK), which wraps the underlying REST API.

You can access Amazon s3 by using command line interface or the AWS management Console, which is a simple web interface.

    Amazon s3 stores data as objects and objects are stored within folders that are called buckets.

 To store an object in Amazon s3 you upload the file you want to store to a bucket. When you upload a file, you can set pemissions on the object so its private  until you want to share it.

Buckets are the containers for objects. You can have one or more buckets. For each bucket, you can control access to the bucket; such as, who can create, delete and list objects in that bucket.

An object can be any kind of file, a text, photo, video, or application.

You can upload entire folder but you must click enable enhanced uploader to install the necessary java applet. Yo only need to do this once per console session.

Home page >> Amazon s3 icon (scalable service in the cloud) >> Create bucket

once bucket created you can not change the name of the bucket. You can chaneg the region. AWS has regions all over the world Different AWS applications are run by region. Utilizing regions can significantly reduce latency to end-users since data or applications they need to access can geographically closer. You can choose Region to optimize letency, minimize costs, address regulator requirements.



Reference :
//video tutorials to learn regarding AWS services.
https://aws.amazon.com/training/intro_series/

//steps to setup IAM account
http://aws.amazon.com/iam/
http://docs.aws.amazon.com/IAM/latest/UserGuide/getting-setup.html

//documentation of aws amazon
http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-arns
https://run.qwiklab.com
 =========================================

AWS Amazon SDK PHP Laravel Implementation

 

* Following setting it need to be done in .env file

AWS_ACCESS_KEY_ID=YOURACCESSKEYID
AWS_SECRET_ACCESS_KEY=YOURSECRETACCESSKEY

AWS_REGION=us-east-1
MEDIA_BUCKET_NAME=BUCKETNAME

Following setting need to add in config/aws.php file

use Aws\Laravel\AwsServiceProvider;

return [

    'credentials' => [
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
    ],
    'region' => env('AWS_REGION', 'us-east-1'),
    's3_bucket' => env('MEDIA_BUCKET_NAME', 'YOURBUCKETNAME'),
    'version' => 'latest',
    'ua_append' => [
        'L5MOD/' . AwsServiceProvider::VERSION,
    ],
    // You can override settings for specific services
    'Ses' => [
        'region' => 'us-east-1',
    ],
];

Example: Upload file to S3 bucket

bellow is the helper function to upload file to s3,

            $fileObj = Input::file('file');
            $file_name = sha1(time() . rand());
            $ext = $fileObj->getClientOriginalExtension();
            $final_url = $file_name . "." . $ext;
            $localTmpFolder = public_path() . "/uploads";
            $fileObj->move($localTmpFolder, $final_url);

            // Upload to S3
            if (Config::get('aws.s3_bucket') != "") {

                //create s3 object
                $s3 = App::make('aws')->createClient('s3');

                //upload the file to AWS Amazon s3 server with public read access
                $media = $s3->putObject([
                    'Bucket' => Config::get('aws.s3_bucket'),
                    'Key' => $final_url,
                    'SourceFile' => $localTmpFolder . "/" . $final_url,
                    'ACL' => 'public-read'
                ]);
   
                //get s3 uploaded url
                $s3_url = $s3->getObjectUrl(Config::get('aws.s3_bucket'), $final_url);

                //unlink the local uploaded file
                unlink($localTmpFolder . '/' . $final_url);
            } else {
                $s3_url = asset('/uploads/' . $final_url);
            }

return $s3_url;



Reference: -
https://github.com/aws/aws-sdk-php-laravel 
 ==========================================================================

Comments

Popular posts from this blog

Learn phpfox

PHPFox  is a social network script, it is an internet application and when you install it, it is a website. The  phpfox  script comes in 3 packages, each with a different set of modules. it has two products: 1. Nebula (upto phpfox 3.8) 2. Neutron (Newer) You can check the demo on :  http://www.phpfox.com =================================================== To clear cache in phpfox follow the following steps, admincp >> Tools >> Maintenance >> Cache Manager >> Click on Clear All button =================================================== To work facebook app on local Following settings need to done in facebook app   1) go => setting => Advance 2) see "OAuth Settings" area and set "Valid OAuth redirect URIs" =  http:// projectdomain /index.php?do=/user/login/, http:// projectdomain .com/index.php?do=/user/register/, http:// projectdomain .com, http:// projectdomain .com/index.php 3) en...

Interview PHP

>> Why do you want to work at our company? Sir, It is a great privilege for anyone to work in a reputed company like yours. When I read about your company I found that my skills are matching your requirements.  Where I can showcase my technical skills to contribute to the company growth. >> What are your strengths? I am very much hard working and optimistic. Hard Working: Work with dedication and determination. Optimistic: work with positive attitude. I am a team player. I am also very hardworking, and will do what it takes to get the job done. >> What are your weaknesses? Gets nervous when talk to strangers I am a bit lazy about which I am not interested I tend to trust people too easily. I am working on it. >> Why should I hire you? With reference to my work experience, I satisfy all the requirement for this job. I am sincere with my work and would never let you down in anyway. I promise you will never regret for the decision to a...

How to Make Your Own PHP Captcha Generator

In this article we will create file based simple yet successful captcha generator. 3 Major Anti-spamming techniques used? Mathematical Operation like Random number + Random Number = -> The user must specify the answer Random word -> User must type the word Random question -> Obvious one which the user should answer correctly [ex: Are you human?] How Captcha works? The captcha generator generates an IMAGE with the question and then put up a session variable storing the value. User input though an input box. Using php POST, we compare the session variable data with the user input and tell whether its a bot or human. Its coding time The Code First let's write the php script which generates the captcha image. We use the simple header-content change technique, from which we can easily bring up an image from a given text. captcha.php PHP Code: array("Num" => "Num"), 1 => array("Are y...