Monday, October 16, 2017
Thursday, May 25, 2017
How to set Deep Linking in Laravel 5.4
How to set Deep Linking in Laravel 5.4:
For this
public function redirectDeepLink(Request $request) {
try {
$device = $this->isMobileDevice();
$id = $request->input('itemId');
$app = config('constant.DEEPLINKING.APP') . $id;
$data = array();
if ($device == 'iPhone') {
$data['primaryRedirection'] = $app;
$data['secndaryRedirection'] = config('constant.DEEPLINKING.APPSTORE');
} else {
$redirect = config('constant.DEEPLINKING.WEBSITE');
return redirect($redirect);
}
return View('deep-linking', $data);
} catch (Exception $e) {
Log::error(__METHOD__ . ' ' . $e->getMessage());
return Utilities::responseError(__('messages.SOMETHING_WENT_WRONG') . $e->getMessage());
}
}
private function isMobileDevice() {
$aMobileUA = array(
'/iphone/i' => 'iPhone',
'/ipod/i' => 'iPod',
'/ipad/i' => 'iPad',
'/android/i' => 'Android',
'/blackberry/i' => 'BlackBerry',
'/webos/i' => 'Mobile'
);
//Return true if Mobile User Agent is detected
foreach ($aMobileUA as $sMobileKey => $sMobileOS) {
if (preg_match($sMobileKey, $_SERVER['HTTP_USER_AGENT'])) {
return $sMobileOS;
}
}
//Otherwise return false..
return false;
}
Here:
config('constant.DEEPLINKING.APP') is Path of App
config('constant.DEEPLINKING.APPSTORE') is Path of App in Appstore
config('constant.DEEPLINKING.WEBSITE') is website domain
in deep-linking.blade.php add this code
<html>
<head>
</head>
<body>
<script>
window.location = "{{$primaryRedirection}}"; // will result in error message if app not installed
setTimeout(function() {
// Link to the App Store should go here -- only fires if deep link fails
window.location = "{{$secndaryRedirection}}";
}, 500);
</script>
</body>
</html>
Thanks
For this
public function redirectDeepLink(Request $request) {
try {
$device = $this->isMobileDevice();
$id = $request->input('itemId');
$app = config('constant.DEEPLINKING.APP') . $id;
$data = array();
if ($device == 'iPhone') {
$data['primaryRedirection'] = $app;
$data['secndaryRedirection'] = config('constant.DEEPLINKING.APPSTORE');
} else {
$redirect = config('constant.DEEPLINKING.WEBSITE');
return redirect($redirect);
}
return View('deep-linking', $data);
} catch (Exception $e) {
Log::error(__METHOD__ . ' ' . $e->getMessage());
return Utilities::responseError(__('messages.SOMETHING_WENT_WRONG') . $e->getMessage());
}
}
private function isMobileDevice() {
$aMobileUA = array(
'/iphone/i' => 'iPhone',
'/ipod/i' => 'iPod',
'/ipad/i' => 'iPad',
'/android/i' => 'Android',
'/blackberry/i' => 'BlackBerry',
'/webos/i' => 'Mobile'
);
//Return true if Mobile User Agent is detected
foreach ($aMobileUA as $sMobileKey => $sMobileOS) {
if (preg_match($sMobileKey, $_SERVER['HTTP_USER_AGENT'])) {
return $sMobileOS;
}
}
//Otherwise return false..
return false;
}
Here:
config('constant.DEEPLINKING.APP') is Path of App
config('constant.DEEPLINKING.APPSTORE') is Path of App in Appstore
config('constant.DEEPLINKING.WEBSITE') is website domain
in deep-linking.blade.php add this code
<html>
<head>
</head>
<body>
<script>
window.location = "{{$primaryRedirection}}"; // will result in error message if app not installed
setTimeout(function() {
// Link to the App Store should go here -- only fires if deep link fails
window.location = "{{$secndaryRedirection}}";
}, 500);
</script>
</body>
</html>
Thanks
Stripe Connect Account with Laravel 5.4
Stripe Connect Account with Laravel 5.4:
In laravel 5.4, I want to use Stripe Connect & payment to this connected account from an another user's card.
For this, firstly connect Stripe Account:
public function getConnect() {
try {
if (isset($_GET['code']) && isset($_GET['state'])) {
$userId = UtilitiesModels::getUserId($_GET['state']);
if ($userId == config('constant.NUMERIC_ZERO')) {
return Utilities::responseError(__('messages.UNAUTHORISED'), config('constant.FOUR_HUNDRED'));
}
$token_request_body = array(
'grant_type' => 'authorization_code',
'client_id' => env('STRIPE_CLIENT_ID'),
'code' => $_GET['code'],
'client_secret' => env('STRIPE_SECRET_KEY')
);
$req = curl_init(env('STRIPE_TOKEN_URI'));
curl_setopt($req, CURLOPT_RETURNTRANSFER, true);
curl_setopt($req, CURLOPT_POST, true);
curl_setopt($req, CURLOPT_POSTFIELDS, http_build_query($token_request_body));
curl_getinfo($req, CURLINFO_HTTP_CODE);
$stripe = json_decode(curl_exec($req), true);
curl_close($req);
if (isset($stripe['stripe_user_id']) && !empty($stripe['stripe_user_id'])) {
UtilitiesModels::updateSellerStripeAcc($userId, $stripe['stripe_user_id']);
$response = redirect()->away(config('constant.HTTP_SUCCESS'));
} else {
$response = redirect()->away(config('constant.HTTP_ERROR'));
}
} else {
$response = redirect()->away(config('constant.HTTP_ERROR'));
}
} catch (Exception $e) {
Log::error(__METHOD__ . ' ' . $e->getMessage());
$response = redirect()->away(config('constant.HTTP_ERROR'));
}
return $response;
}
Now i want to charge amount from first stripe token (which we get from card details) & then transfer to this connected stripe account
Stripe::setApiKey(env('STRIPE_SECRET_KEY'));
$charge = Charge::create(array(
'source' => $request->buyerStripeToken,
'amount' => $request->amount * config('constant.HUNDRED'),
'currency' => 'aud',
'description' => __('messages.PAYMENT_FROM_BUYER'),
'destination' => array(
"amount" => $sellerEntity->price * config('constant.HUNDRED'),
"account" => $user->seller_stripe_account
),
));
Here:
$_GET['code'] is the code which we get from Stripe after Stripe Auth.
$_GET['state'] is access token which we get from front end for getting user id.
env('STRIPE_CLIENT_ID') is stripe client id.
env('STRIPE_SECRET_KEY') is stripe secret key.
env('STRIPE_TOKEN_URI') is https://connect.stripe.com/oauth/token
config('constant.HTTP_SUCCESS') is http://success
config('constant.HTTP_ERROR') is http://error
$request->buyerStripeToken is Stripe token which comes from stripe card
$request->amount is amount which we deduct
$sellerEntity->price is amount which we transfer to Stripe Account
$user->seller_stripe_account is connected Stripe Account
Thanks
In laravel 5.4, I want to use Stripe Connect & payment to this connected account from an another user's card.
For this, firstly connect Stripe Account:
public function getConnect() {
try {
if (isset($_GET['code']) && isset($_GET['state'])) {
$userId = UtilitiesModels::getUserId($_GET['state']);
if ($userId == config('constant.NUMERIC_ZERO')) {
return Utilities::responseError(__('messages.UNAUTHORISED'), config('constant.FOUR_HUNDRED'));
}
$token_request_body = array(
'grant_type' => 'authorization_code',
'client_id' => env('STRIPE_CLIENT_ID'),
'code' => $_GET['code'],
'client_secret' => env('STRIPE_SECRET_KEY')
);
$req = curl_init(env('STRIPE_TOKEN_URI'));
curl_setopt($req, CURLOPT_RETURNTRANSFER, true);
curl_setopt($req, CURLOPT_POST, true);
curl_setopt($req, CURLOPT_POSTFIELDS, http_build_query($token_request_body));
curl_getinfo($req, CURLINFO_HTTP_CODE);
$stripe = json_decode(curl_exec($req), true);
curl_close($req);
if (isset($stripe['stripe_user_id']) && !empty($stripe['stripe_user_id'])) {
UtilitiesModels::updateSellerStripeAcc($userId, $stripe['stripe_user_id']);
$response = redirect()->away(config('constant.HTTP_SUCCESS'));
} else {
$response = redirect()->away(config('constant.HTTP_ERROR'));
}
} else {
$response = redirect()->away(config('constant.HTTP_ERROR'));
}
} catch (Exception $e) {
Log::error(__METHOD__ . ' ' . $e->getMessage());
$response = redirect()->away(config('constant.HTTP_ERROR'));
}
return $response;
}
Now i want to charge amount from first stripe token (which we get from card details) & then transfer to this connected stripe account
Stripe::setApiKey(env('STRIPE_SECRET_KEY'));
$charge = Charge::create(array(
'source' => $request->buyerStripeToken,
'amount' => $request->amount * config('constant.HUNDRED'),
'currency' => 'aud',
'description' => __('messages.PAYMENT_FROM_BUYER'),
'destination' => array(
"amount" => $sellerEntity->price * config('constant.HUNDRED'),
"account" => $user->seller_stripe_account
),
));
Here:
$_GET['code'] is the code which we get from Stripe after Stripe Auth.
$_GET['state'] is access token which we get from front end for getting user id.
env('STRIPE_CLIENT_ID') is stripe client id.
env('STRIPE_SECRET_KEY') is stripe secret key.
env('STRIPE_TOKEN_URI') is https://connect.stripe.com/oauth/token
config('constant.HTTP_SUCCESS') is http://success
config('constant.HTTP_ERROR') is http://error
$request->buyerStripeToken is Stripe token which comes from stripe card
$request->amount is amount which we deduct
$sellerEntity->price is amount which we transfer to Stripe Account
$user->seller_stripe_account is connected Stripe Account
Thanks
Saturday, February 25, 2017
Convert to camel case and snake case in php
Convert to camel case and snake case in php:
In php, if we want to convert camel case to snake case and vise versa then we have to use following methods:public static function convertToCamelCase($array) {
$converted_array = [];
foreach ($array as $old_key => $value) {
if (is_array($value)) {
$value = static::convertToCamelCase($value);
} else if (is_object($value)) {
if (method_exists($value, 'toArray')) {
$value = $value->toArray();
} else {
$value = (array) $value;
}
$value = static::convertToCamelCase($value);
}
$converted_array[camel_case($old_key)] = $value;
}
return $converted_array;
}
public static function convertToSnakeCase($array) {
$converted_array = [];
foreach ($array as $old_key => $value) {
if (is_array($value)) {
$value = static::convertToSnakeCase($value);
} else if (is_object($value)) {
if (method_exists($value, 'toArray')) {
$value = $value->toArray();
} else {
$value = (array) $value;
}
$value = static::convertToSnakeCase($value);
}
$new_key = ltrim(strtolower(preg_replace('/[A-Z]/', '_$0', $old_key)), '_');
$converted_array[$new_key] = $value;
}
return $converted_array;
}
This will help for this.
Laravel 5.4 validation for age lesser than 18
Laravel 5.4 validation for age lesser than 18:
In laravel 5.4 validation we have only min & max value , which counts the number.
If in such case we have to validate age then this will not help.
For this we have to use regex like this:
'age' => ['required','numeric','regex:/^(?:[1-9]\d{2,}+|[2-9]\d|1[89])$/i'],
It will not allow age lesser than 18
Thanks
Laravel multi select box get old value
Laravel multi select box get old value:
Hi, Some time we want to get old values in laravel (when there is some validation apply on a form.).In this case, genrally we are unable to get old value for a multiple select box.
For this use this code:
<select name="tribe[]" id="tags" class="form-control" multiple>
@if (is_array(old('tribe')))
@foreach ($tribes as $tribe)
<option value="{{ $tribe->id }}" <?php if(in_array($tribe->id, old('tribe'))) {echo 'selected';} ?> >{{ $tribe->name }}</option>
@endforeach
@else
@foreach ($tribes as $tribe)
<option value="{{ $tribe->id }}" >{{ $tribe->name }}</option>
@endforeach
@endif
</select>
This will help for get old values in multiple select box.
Thanks
Saturday, November 19, 2016
Laravel 5.3 search bar using jquery Autocomplete
Laravel 5.3 search bar using jquery Autocomplete:
For set up search bar in Laravel 5.3, we have to do the folloing things:
In your blade file write this code:
Also add jquery library in your code which is mentioned in this code.
<input id="surgeon-name" type="text" class="form-control pd-l-50" placeholder="SEARCH BY SURGEON NAME">
<script src="{{asset('js/jquery-1.12.4.js')}}"></script>
<script src="{{asset('js/jquery-ui.js')}}"></script>
<script>
(function () {
src = "/prefcard/maker-search-surgeon";
$("#surgeon-name").autocomplete({
source: function (request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response(data);
}
});
},
min_length: 3,
select: function (event, ui)
{
// console.log(ui.item.value);return false;
var test = ui.item.value ? ui.item.value : '';
if (test != '')
{
var url = '/prefcard/maker-search-surgeon';
var formAutocomplete = $('<form action="' + url + '" method="post">' +
'<input type="hidden" name="_token" value="{{ csrf_token() }}">' +
'<input type="text" name="term" value="' + ui.item.value + '" />' +
'</form>');
$('body').append(formAutocomplete);
formAutocomplete.submit();
}
}
});
})();
</script>
In your routes file write this code
Route::get('maker-search-surgeon', 'SearchController@searchSurgeon');
Route::post('maker-search-surgeon', 'SearchController@postSearchSurgeon');
In your SearchController create two method
public function searchSurgeon(Request $request) {
$query = $request->get('term', '');
$results = DB::table('surgeon')
->where('firstname', 'LIKE', '%' . $query . '%')
->orWhere('lastname', 'LIKE', '%' . $query . '%')
->take(5)->get();
$data = array();
foreach ($results as $result) {
$data[] = array('value' => $result->firstname . ' ' . $result->lastname, 'id' => $result->id);
}
if (count($data))
return $data;
else
return ['value' => 'No Result Found', 'id' => ''];
}
public function postSearchSurgeon(Request $request) {
//Do whatever you want to search accordingly name and then return
return view('dashboard')->with('surgeon', $surgeon);
}
Thanks
For set up search bar in Laravel 5.3, we have to do the folloing things:
In your blade file write this code:
Also add jquery library in your code which is mentioned in this code.
<input id="surgeon-name" type="text" class="form-control pd-l-50" placeholder="SEARCH BY SURGEON NAME">
<script src="{{asset('js/jquery-1.12.4.js')}}"></script>
<script src="{{asset('js/jquery-ui.js')}}"></script>
<script>
(function () {
src = "/prefcard/maker-search-surgeon";
$("#surgeon-name").autocomplete({
source: function (request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response(data);
}
});
},
min_length: 3,
select: function (event, ui)
{
// console.log(ui.item.value);return false;
var test = ui.item.value ? ui.item.value : '';
if (test != '')
{
var url = '/prefcard/maker-search-surgeon';
var formAutocomplete = $('<form action="' + url + '" method="post">' +
'<input type="hidden" name="_token" value="{{ csrf_token() }}">' +
'<input type="text" name="term" value="' + ui.item.value + '" />' +
'</form>');
$('body').append(formAutocomplete);
formAutocomplete.submit();
}
}
});
})();
</script>
In your routes file write this code
Route::get('maker-search-surgeon', 'SearchController@searchSurgeon');
Route::post('maker-search-surgeon', 'SearchController@postSearchSurgeon');
In your SearchController create two method
public function searchSurgeon(Request $request) {
$query = $request->get('term', '');
$results = DB::table('surgeon')
->where('firstname', 'LIKE', '%' . $query . '%')
->orWhere('lastname', 'LIKE', '%' . $query . '%')
->take(5)->get();
$data = array();
foreach ($results as $result) {
$data[] = array('value' => $result->firstname . ' ' . $result->lastname, 'id' => $result->id);
}
if (count($data))
return $data;
else
return ['value' => 'No Result Found', 'id' => ''];
}
public function postSearchSurgeon(Request $request) {
//Do whatever you want to search accordingly name and then return
return view('dashboard')->with('surgeon', $surgeon);
}
Thanks
How to put dynamic name of functions in javascript?
Dynamic names of functions in javascript:
In some conditions we are in need of dynamic function names.
In js we can do this by creating classes.
for e.g.
var surgeonVal = 1; // value for id
function surgeonPagination() {
$('.nav-next').click(function (e) { // next button clicked
var result = Class.callFunc(surgeonVal);
surgeonVal++;
});
}
var Class = (function (window) {
return {
1: function () {
//Do some work
},
2: function () {
//Do some work
}
},
3: function () {
//Do some work
},
callFunc: function (funcName) {
return this[funcName]();
}
};
})(window);
In this above example I want to call some functions as accordingly to change value of "surgeonVal". So I create a class and call it's function as accordingly.
Thanks
In some conditions we are in need of dynamic function names.
In js we can do this by creating classes.
for e.g.
var surgeonVal = 1; // value for id
function surgeonPagination() {
$('.nav-next').click(function (e) { // next button clicked
var result = Class.callFunc(surgeonVal);
surgeonVal++;
});
}
var Class = (function (window) {
return {
1: function () {
//Do some work
},
2: function () {
//Do some work
}
},
3: function () {
//Do some work
},
callFunc: function (funcName) {
return this[funcName]();
}
};
})(window);
In this above example I want to call some functions as accordingly to change value of "surgeonVal". So I create a class and call it's function as accordingly.
Thanks
Friday, September 9, 2016
How to by pass Laravel Authentication based on password
How to by pass Laravel Authentication based on password:
I want to create a SuperAdmin for my app, who can login all the account of his database.
For this I want to bypass all the authentication using a password. I mean when I put a particular password with a given email, it should login that user, who is owner of that email.
For this go to your AuthController.php. Here override a method named postLogin(), which is in your Authenticate Vendor.
In this method, change some code like this
change this:
if (Auth::attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
to:
if($credentials['password']=='ashishginotra'){
$user = User::where('email',$credentials['email'])->first();
Auth::login($user);
}else {
if (Auth::attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
}
Here "ashishginotra" is my default password.
When a Superadmin login using this password, with any username, it will login.
Thanks
I want to create a SuperAdmin for my app, who can login all the account of his database.
For this I want to bypass all the authentication using a password. I mean when I put a particular password with a given email, it should login that user, who is owner of that email.
For this go to your AuthController.php. Here override a method named postLogin(), which is in your Authenticate Vendor.
In this method, change some code like this
change this:
if (Auth::attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
to:
if($credentials['password']=='ashishginotra'){
$user = User::where('email',$credentials['email'])->first();
Auth::login($user);
}else {
if (Auth::attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
}
Here "ashishginotra" is my default password.
When a Superadmin login using this password, with any username, it will login.
Thanks
Friday, September 2, 2016
Get video url using bucket path of aws s3 in laravel 5.2
Get video url using bucket path of aws s3 in laravel 5.2
I have bucket path of AWS S3 video and I want to get a streaming video url from AWS CloudFront.
For this, Firstly I have to install AWS SDK in my project.
In composer.json , put it
"aws/aws-sdk-php-laravel": "~3.0"
and run composer update.
In app.php file write this in providers
Aws\Laravel\AwsServiceProvider::class,
and in aliases
'AWS' => Aws\Laravel\AwsFacade::class,
Now goto your controller and include this
use Aws\CloudFront\CloudFrontClient;
Now create a method like this
Here $video is bucket video name, and in env variables these are CloudFront url,
private key, aws key pair id which you get from aws and write in your .env file.
Thanks
I have bucket path of AWS S3 video and I want to get a streaming video url from AWS CloudFront.
For this, Firstly I have to install AWS SDK in my project.
In composer.json , put it
"aws/aws-sdk-php-laravel": "~3.0"
and run composer update.
In app.php file write this in providers
Aws\Laravel\AwsServiceProvider::class,
and in aliases
'AWS' => Aws\Laravel\AwsFacade::class,
Now goto your controller and include this
use Aws\CloudFront\CloudFrontClient;
Now create a method like this
public static function getVideoUrl($video){
try {
$cloudFront = CloudFrontClient::factory([
'region' => 'us-east-1',
'version' => 'latest'
]);
$expiry = new \DateTime('+5256000 minutes');
return $cloudFront->getSignedUrl([
'url' => env('AWS_CLOUDFRONT_URL') . "/$video",
'expires' => $expiry->getTimestamp(),
'private_key' => public_path() . '/' . env('AWS_PRIVATE_KEY'),
'key_pair_id' => env('AWS_KEY_PAIR_ID')
]);
} catch (Exception $e) {
return 'false';
}}
Here $video is bucket video name, and in env variables these are CloudFront url,
private key, aws key pair id which you get from aws and write in your .env file.
Thanks
Friday, August 26, 2016
How to use job(queue) with redis server in laravel 5.2
How to use job(queue) with redis server in laravel 5.2:
For using jobs in Laravel 5.2 with redis server, we have to do following steps:
1. First to install redis server on your machine for this, run this command on your terminal
sudo apt install redis-server
It will install your redis server. For start redis server run this command
redis-server
2. Now install the dependency in your project. For this write this in your composer.json
predis/predis ~1.0
and update composer via
composer update
3. Now do some settings
(a) In .env file change QUEUE_DRIVER=sync to QUEUE_DRIVER=redis
(b) In config/queue.php file change 'default' => env('QUEUE_DRIVER', 'redis')
(c) In config/session.php file change 'driver' => env('SESSION_DRIVER', 'redis')
4. Now run this command on terminal for create a new queue
php artisan make:job InsertFeedData
5. Now go to this file job/InsertFeedData.php and write your code in handle function which you want to run as a job.
class InsertFeedData extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $user;
protected $video;
protected $type;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($user, $video, $type)
{
$this->user = $user;
$this->video = $video;
$this->type = $type;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$followers = Follower::where('user_id', $this->user)->pluck('follower_id');
Feed::create(['video_id' => $this->video, 'follower_id' => $this->user, 'type' => $this->type]);
foreach ($followers as $follower) {
$feed = Feed::create(['video_id' => $this->video, 'follower_id' => $follower, 'type' => $this->type]);
print_r($feed);
}
}
}
6. Now you can use this class in your controller via
7. You can check it via running this command on terminal
php artisan queue:listen
Thanks
For using jobs in Laravel 5.2 with redis server, we have to do following steps:
1. First to install redis server on your machine for this, run this command on your terminal
sudo apt install redis-server
It will install your redis server. For start redis server run this command
redis-server
2. Now install the dependency in your project. For this write this in your composer.json
predis/predis ~1.0
and update composer via
composer update
3. Now do some settings
(a) In .env file change QUEUE_DRIVER=sync to QUEUE_DRIVER=redis
(b) In config/queue.php file change 'default' => env('QUEUE_DRIVER', 'redis')
(c) In config/session.php file change 'driver' => env('SESSION_DRIVER', 'redis')
4. Now run this command on terminal for create a new queue
php artisan make:job InsertFeedData
5. Now go to this file job/InsertFeedData.php and write your code in handle function which you want to run as a job.
class InsertFeedData extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $user;
protected $video;
protected $type;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($user, $video, $type)
{
$this->user = $user;
$this->video = $video;
$this->type = $type;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$followers = Follower::where('user_id', $this->user)->pluck('follower_id');
Feed::create(['video_id' => $this->video, 'follower_id' => $this->user, 'type' => $this->type]);
foreach ($followers as $follower) {
$feed = Feed::create(['video_id' => $this->video, 'follower_id' => $follower, 'type' => $this->type]);
print_r($feed);
}
}
}
6. Now you can use this class in your controller via
$this->dispatch(new InsertFeedData(Utilities::getUserId(), $video->id, 'share'));
7. You can check it via running this command on terminal
php artisan queue:listen
Thanks
Friday, August 19, 2016
Search a full text using scout in Laravel 5.3
Search a full text using scout in Laravel 5.3:
In Laravel 5.3 we can search a full text using scout.
For this we have to import it in that model.
In Laravel 5.3 we can search a full text using scout.
For this we have to import it in that model.
php artisan scout:import App\\Post
After that we can use it in model like this.Post::search('Alice')->get();
Also we can use it in pagination.Post::search('Alice')->paginate()
Also, we can use in simple where clauses.Post::search(‘Alice’)—>where('acount_id', '>', 1)->paginate()
ThanksSaturday, August 13, 2016
Laravel collection function for easy fetching data
Laravel collection function for easy fetching data:
For fetching data in easy way :
Let us assume I'm fetching an object form a table Likes and want to know, it is liked by which users.
For this :
It will be very easy way for getting value from this collection object.
Thanks
For fetching data in easy way :
Let us assume I'm fetching an object form a table Likes and want to know, it is liked by which users.
For this :
$v->likes->keyBy('liked_by')->has($userId);
It will be very easy way for getting value from this collection object.
Thanks
Saturday, August 6, 2016
Install mysql without getting password prompt
Install mysql without getting password prompt :
For installing mysql without password prompt, we will run following command:
sudo debconf-set-selections <<< "mysql-server mysql-server/root_password password root"
sudo debconf-set-selections <<< "mysql-server mysql-server/root_password_again password root
sudo apt-get install mysql-server
After running these command, it will not ask for password. It will be set "root" password
Thanks
For installing mysql without password prompt, we will run following command:
sudo debconf-set-selections <<< "mysql-server mysql-server/root_password password root"
sudo debconf-set-selections <<< "mysql-server mysql-server/root_password_again password root
sudo apt-get install mysql-server
After running these command, it will not ask for password. It will be set "root" password
Thanks
Friday, July 29, 2016
IE Blocking iFrame Cookies
IE Blocking iFrame Cookies :
Today we will discuss about "IE Blocking iFrame Cookies".
I have faced a problem in my applications not running correctly from inside an iFrame. I tried it out and it looked like everything worked great in Safari and Firefox but not IE6 or IE7. It took me a few failed attempts to fix it before I decided it must be a session problem. After firing up a packet sniffer it became obvious the cookie with the session ID was not being passed.
The problem lies with a W3C standard called Platform for Privacy Preferences or P3P for short. You can read all about the boring stuff via the link or else just install the P3P Compact Policy header below. This will allow Internet Explorer to accept your third-party cookie. You will need to send the header on every page that sets a cookie.
PHP:
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
Thanks
Today we will discuss about "IE Blocking iFrame Cookies".
I have faced a problem in my applications not running correctly from inside an iFrame. I tried it out and it looked like everything worked great in Safari and Firefox but not IE6 or IE7. It took me a few failed attempts to fix it before I decided it must be a session problem. After firing up a packet sniffer it became obvious the cookie with the session ID was not being passed.
The problem lies with a W3C standard called Platform for Privacy Preferences or P3P for short. You can read all about the boring stuff via the link or else just install the P3P Compact Policy header below. This will allow Internet Explorer to accept your third-party cookie. You will need to send the header on every page that sets a cookie.
PHP:
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
Thanks
Friday, July 22, 2016
How to implement shopping cart in laravel 5
How to implement shopping cart in laravel 5:
For implement shopping cart in your application we have to follow following steps:
1. In your composer.json file write the following code in require:
"gloudemans/shoppingcart": "^2.1",
then run command composer update.
2. In config/app.php write the following code.
In providers:
\Gloudemans\Shoppingcart\ShoppingcartServiceProvider::class
In aliases:
'Cart' => \Gloudemans\Shoppingcart\Facades\Cart::class,
Now we can use cart in our applications
for add product in cart:
Cart::add('293ad', 'Product 1', 1, 9.99);
Here first parms is product id, 2nd is name of product, 3rd quantity and 4th is price of product
for update:
Cart::update($rowId, 2);
Here $rowId is a unique id product wise which is generate automatically.
2nd params is the quantity, which we want to increase.
for remove:
Cart::remove($rowId);
for check the cart:
Cart::content();
for destroy cart:
Cart::destroy();
for total in cart:
Cart::total();
for count in cart:
Cart::count();
Thanks
For implement shopping cart in your application we have to follow following steps:
1. In your composer.json file write the following code in require:
"gloudemans/shoppingcart": "^2.1",
then run command composer update.
2. In config/app.php write the following code.
In providers:
\Gloudemans\Shoppingcart\ShoppingcartServiceProvider::class
In aliases:
'Cart' => \Gloudemans\Shoppingcart\Facades\Cart::class,
Now we can use cart in our applications
for add product in cart:
Cart::add('293ad', 'Product 1', 1, 9.99);
Here first parms is product id, 2nd is name of product, 3rd quantity and 4th is price of product
for update:
Cart::update($rowId, 2);
Here $rowId is a unique id product wise which is generate automatically.
2nd params is the quantity, which we want to increase.
for remove:
Cart::remove($rowId);
for check the cart:
Cart::content();
for destroy cart:
Cart::destroy();
for total in cart:
Cart::total();
for count in cart:
Cart::count();
Thanks
Friday, July 8, 2016
Updating Column Types with Laravel's Schema Builder
Laravel makes database migrations very easy with its Schema Builder. It has a lot of built-in methods to add tables, columns, indexes, etc. However, it's easy to forget that you can do so much more with just plain old SQL queries.
I needed to change the type of a column from VARCHAR to TEXT. Here's what I ran in a migration file:
public function up()
{
DB::statement('ALTER TABLE flavours MODIFY COLUMN description TEXT');
}
public function down()
{
DB::statement('ALTER TABLE flavours MODIFY COLUMN description VARCHAR(255)');
}
I think this will make you little help.
Thanks.
I needed to change the type of a column from VARCHAR to TEXT. Here's what I ran in a migration file:
public function up()
{
DB::statement('ALTER TABLE flavours MODIFY COLUMN description TEXT');
}
public function down()
{
DB::statement('ALTER TABLE flavours MODIFY COLUMN description VARCHAR(255)');
}
I think this will make you little help.
Thanks.
Friday, June 24, 2016
Angular 2 Beginning using Component
Angular 2 Beginning using Component:
In beginning, open app.component.ts file and write the code in it.
Add this code in your file and run
npm strat.
This will show the output.
Thanks
In beginning, open app.component.ts file and write the code in it.
import {Component} from 'angular2/core'; @Component({ selector: 'my-app', template: ` <h1 (click)="onSelect()">Ashish Ginotra's</h1> <p>Hello World!</p> <h1 *ngIf="showDetail === true">This is {{contact.lastname}}</h1> <input [(ngModel)]="contact.lastname" type="text"> `, }) export class AppComponent { public contact = {firstname:"Ashish",lastname:"Ginotra"}; public showDetail = false; onSelect(){ this.showDetail = true; } }
Add this code in your file and run
npm strat.
This will show the output.
Thanks
Friday, June 17, 2016
Token Mismatch error on login page Laravel 5
Token Mismatch error on login page Laravel 5:
Sometimes we noticed on the login page of Laravel 5, when we leave this page for sometimes and then click on login button, then it shows token mismatch error.
This is because session time of laravel has been expired and current token for that page do not match the actual page.
For prevent this kind of error, we have to handle it.
Goto this file : app/Exceptions/Handler.php
and add this code in render function.
public function render($request, Exception $e)
{
if ($e instanceof \Illuminate\Session\TokenMismatchException) {
return redirect()->guest('auth/login');
}
return parent::render($request, $e);
}
Thanks
Sometimes we noticed on the login page of Laravel 5, when we leave this page for sometimes and then click on login button, then it shows token mismatch error.
This is because session time of laravel has been expired and current token for that page do not match the actual page.
For prevent this kind of error, we have to handle it.
Goto this file : app/Exceptions/Handler.php
and add this code in render function.
public function render($request, Exception $e)
{
if ($e instanceof \Illuminate\Session\TokenMismatchException) {
return redirect()->guest('auth/login');
}
return parent::render($request, $e);
}
Thanks
Friday, June 10, 2016
Resize image in Laravel 5
Resize image in Laravel 5:
For resizing image in laravel:
Firstly we have to install a package. For this open your composer.json and write this code in require.
"intervention/image": "dev-master"
then run composer update
In config/app.php write this code in aliases
'Image' => Intervention\Image\Facades\Image::class,
and this in providers
Intervention\Image\ImageServiceProvider::class,
Now go to your controller & use this.
use Intervention\Image\Facades\Image;
Now go to your method and write this code
$dirName = 'path/of/image';
$img = Image::make($dirName . "/background.jpg")->resize(720, 1280);
$img->save($dirName . "/background.jpg");
Thanks
For resizing image in laravel:
Firstly we have to install a package. For this open your composer.json and write this code in require.
"intervention/image": "dev-master"
then run composer update
In config/app.php write this code in aliases
'Image' => Intervention\Image\Facades\Image::class,
and this in providers
Intervention\Image\ImageServiceProvider::class,
Now go to your controller & use this.
use Intervention\Image\Facades\Image;
Now go to your method and write this code
$dirName = 'path/of/image';
$img = Image::make($dirName . "/background.jpg")->resize(720, 1280);
$img->save($dirName . "/background.jpg");
Thanks
Subscribe to:
Posts (Atom)