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 cacheCache::tags('admins')->flush();
=========================================================================
Access module specific varable in config
# access module specific varable in configecho "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();
=========================================================================
\Module::asset('admin:');
OR
\Pingpong\Modules\Facades\Module::asset('admin:');
# get module path
\Pingpong\Modules\Facades\Module::getModulePath('admin');
=========================================================================
{!! 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']) !!}
=========================================================================
$route = $request->route();
$uri = $route->getUri();
$action = $request->route()->getAction();
=========================================================================
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();
});
=========================================================================
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;');
}
}
=========================================================================
$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');
}
\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 syntaxSchema::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 tablesuse 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 datatableshttps://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
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
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
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');
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
==========================================================================
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',
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 :
- The two key fields type and/or size doesn’t match exactly. For example, if one is
INT(10)the key field needs to beINT(10)as well and notINT(11)orTINYINT. You may want to confirm the field size usingSHOWCREATETABLEbecause Query Browser will sometimes visually show justINTEGERfor bothINT(10)andINT(11). You should also check that one is notSIGNEDand the other isUNSIGNED. They both need to be exactly the same. - 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.
- 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.
- One or both of your tables is a
MyISAMtable. In order to use foreign keys, the tables must both beInnoDB. (Actually, if both tables areMyISAMthen you won’t get an error message - it just won’t create the key.) In Query Browser, you can specify the table type. - You have specified a cascade
ONDELETESETNULL, but the relevant key field is set toNOTNULL. You can fix this by either changing your cascade or setting the field to allowNULLvalues. - 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.
- You have a default value (ie default=0) on your foreign key column
- 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.
- You have a syntax error in your
ALTERstatement or you have mistyped one of the field names in the relationship - 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
Post a Comment