IamCrazyD

PHP Programmer at Mumbai

Experience

19,335

0 Best Reply Awards

  • Member Since 2 Years Ago
  • 253 Lessons Completed
  • 0 Favorites

21st August, 2017

IamCrazyD started a new conversation PHP - Mkdir Permission Denied On Digital Ocean • 3 months ago

0 down vote favorite I have deployed my Laravel application on DigitalOcean (without any third party packge usage). The application is functioning fine, except for uploading of files by the users.

I have installed LEMP stack by following the guide of DevMarketer (YouTube playlist).

Scenario:

I want to upload the file and store in my public directory. But, doing so, I get the error as Permission Denied.

Here's the code of directory that will get created it if not exist:

$path = public_path() . '/email-attachments/';

if (! file_exists($path)) {
    mkdir($path, 0775, true);
}

On SSHing on to the server as root, I ran the following command to check the permission of the files and folders:

[email protected]:~# ls -la /var/www/laravel
total 456
drwxrwsr-x 12 www-data www-data   4096 Aug 21 09:45 .
drwxrwsr-x  4 www-data www-data   4096 Aug 18 07:13 ..
-rwxrwxr-x  1 www-data www-data    665 Aug 21 08:23 .env
-rw-rwSr--  1 www-data www-data    521 Aug 21 09:45 .env.example
-rw-rwSr--  1 www-data www-data    111 Aug 21 09:45 .gitattributes
-rw-rwSr--  1 www-data www-data    157 Aug 21 09:45 .gitignore
drwxrwsr-x  8 www-data www-data   4096 Aug 21 09:45 app
-rw-rwSr--  1 www-data www-data   1646 Aug 21 09:45 artisan
drwxrwsr-x  3 www-data www-data   4096 Aug 21 09:45 bootstrap
-rw-rwSr--  1 www-data www-data   1496 Aug 21 09:45 composer.json
-rw-rwSr--  1 www-data www-data 150371 Aug 21 09:45 composer.lock
drwxrwsr-x  2 www-data www-data   4096 Aug 21 09:45 config
drwxrwsr-x  5 www-data www-data   4096 Aug 21 09:45 database
-rw-rwSr--  1 www-data www-data   1063 Aug 21 09:45 package.json
-rw-rwSr--  1 www-data www-data   1100 Aug 21 09:45 phpunit.xml
drwxrwsr-x 10 www-data www-data   4096 Aug 21 09:45 public
-rwxrwxr-x  1 www-data www-data    440 Aug 21 06:27 queue_worker.log
drwxrwsr-x  5 www-data www-data   4096 Aug 18 07:56 resources
drwxrwsr-x  2 www-data www-data   4096 Aug 21 09:45 routes
-rw-rwSr--  1 www-data www-data    563 Aug 21 09:45 server.php
drwxrwsr-x  6 www-data www-data   4096 Aug 18 07:56 storage
drwxrwsr-x  4 www-data www-data   4096 Aug 21 09:45 tests
drwxrwsr-x 39 www-data www-data   4096 Aug 21 05:58 vendor
-rw-rwSr--  1 www-data www-data   1439 Aug 21 09:45 webpack.mix.js
-rw-rwSr--  1 www-data www-data 212974 Aug 21 09:45 yarn.lock

Following is the result of ps -ef | grep nginx

[email protected]:~# ps -ef | grep nginx
root     14862     1  0 11:45 ?        00:00:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
www-data 14863 14862  0 11:45 ?        00:00:00 nginx: worker process
root     15489 12952  0 12:19 pts/0    00:00:00 grep --color=auto nginx

Following is the result of ps -ef | grep php

[email protected]:~# ps -ef | grep php
root     10173  9901  0 05:05 ?        00:00:16 php /var/www/laravel/artisan queue:work --tries=5
root     10174  9901  0 05:05 ?        00:00:15 php /var/www/laravel/artisan queue:work --tries=5
root     10175  9901  0 05:05 ?        00:00:16 php /var/www/laravel/artisan queue:work --tries=5
root     10176  9901  0 05:05 ?        00:00:16 php /var/www/laravel/artisan queue:work --tries=5
root     10177  9901  0 05:05 ?        00:00:15 php /var/www/laravel/artisan queue:work --tries=5
root     10178  9901  0 05:05 ?        00:00:15 php /var/www/laravel/artisan queue:work --tries=5
root     10179  9901  0 05:05 ?        00:00:15 php /var/www/laravel/artisan queue:work --tries=5
root     10180  9901  0 05:05 ?        00:00:16 php /var/www/laravel/artisan queue:work --tries=5
root     15251     1  0 11:50 ?        00:00:00 php-fpm: master process (/etc/php/5.6/fpm/php-fpm.conf)
www-data 15255 15251  0 11:50 ?        00:00:02 php-fpm: pool www
www-data 15256 15251  0 11:50 ?        00:00:02 php-fpm: pool www
root     15495 12952  0 12:21 pts/0    00:00:00 grep --color=auto php

I don't know what is the mistake that I am doing (I know it must be a silly one), but I couldn't find the solution yet.

Please help me out with this. Thanks.

10th June, 2017

IamCrazyD started a new conversation Laravel 5.4 Send Mail With Attachment Giving Error - Using Mailtrap.io • 5 months ago

I am trying to send email with an attachment in a developing environment - using mailtrap for the same. This attachment can be of any file type. But, I always end up receiving the error:

Expected response code 250 but got code "502", 
with message "502 5.5.2 Error: command not recognized

I don't know where and what mistake I am doing, but I am failing to achieve the desired result and that is send the mail with an attachment.

The attachment file resides inside the public/email-attachments/ folder

Here's the code that I have tried so far:

/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
    $mailContent = cache('allEmailContents')->first();

    return $this->from('[email protected]')
                ->subject($mailContent->subject)
                ->view('emails.send')
                ->attach($mailContent->attachment, [
                    'as' => str_slug($mailContent->subject),
                    'mime' => File::mimeType($mailContent->attachment)
                ])
                ->with(['mailContent' => $mailContent]);
}

And in the routes/web.php file:

Route::get('/', function() {
    Mail::to('[email protected]')
            ->send(new SendWelcomeEmail());

    return view('welcome');
});

I have also tried the old way of sending mail to no success:

Route::get('/', function() {
    $mailContent = cache('allEmailContents')->first();
    $data = $mailContent->toArray();

    Mail::send('emails.send', $data, function($mail) use ($mailContent, $data) {    
        $mail->to('[email protected]')->subject($mailContent->subject);
        $mail->from('[email protected]');
        $mail->attach($mailContent->attachment, [
            'as' => str_slug($mailContent->subject),
            'mime' => File::mimeType($mailContent->attachment)
        ])
    });

    return view('welcome');
});

Kindly help me out with this. Any help is highly appreciated.

29th December, 2016

IamCrazyD left a reply on Laravel 5.3 Queues Not Working In Shared Hosting • 10 months ago

@Snapey I have updated the question, kindly have a look at it. I have provided the stack trace of from laravel.log file.

28th December, 2016

IamCrazyD left a reply on Laravel 5.3 Queues Not Working In Shared Hosting • 10 months ago

It is the same as what I have provided in the question above.

IamCrazyD left a reply on Laravel 5.3 Queues Not Working In Shared Hosting • 10 months ago

Got this exception in failed_jobs table..

Connection could not be established with host mailtrap.io

What should I do next?

IamCrazyD started a new conversation Laravel 5.3 Queues Not Working In Shared Hosting • 10 months ago

In my Laravel 5.3.* application, I am having queues running in the background. This works completely fine in my local machine. But when this is made live on the server (shared hosting), it doesn't work at all.

Here's the scenario:

  1. Administrator is submitting the admin generator form data.

  2. Data is getting inserted in the database.

  3. Shoot an email regarding the same.

So, in order to have this functionality going smoothly, I have created a cron job on my server's cPanel.

/usr/local/bin/php /home/<username>/laravel-app/artisan schedule:run >/dev/null 2>&1

And here's the app/Console/Kernel.php file content

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
    // $schedule->command('inspire')
    //          ->hourly();

    $schedule->command('queue:work --daemon --tries=3')
             ->everyMinute()
             ->withoutOverlapping();
}

And I have also created the database for jobs by running

php artisan queue:table;
php artisan queue:failed-table;
php artisan migrate;

When the administrator is generated/inserted, an event is fired:

event(new AdministratorHasBeenGenerated($user, $request->password));

which will send a welcome email to the provided email id (in app/Listeners/AdministratorHasBeenGenerated/SendWelcomeEmail.php)

/**
 * Handle the event.
 *
 * @param  AdministratorHasBeenGenerated  $event
 * @return void
 */
public function handle(AdministratorHasBeenGenerated $event)
{
    Mail::to($event->administrator->email)
          ->queue(new GeneratedMail($event->administrator, $event->password));
}

And here's the mail configs in the .env file

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=correct_username
MAIL_PASSWORD=correct_password
MAIL_ENCRYPTION=null

I don't receive any errors or things as such, but neither I receive any welcome email even though I provide correct email id.

Can anybody point out the mistake as to where and what I must have done? It has been more than 4 hours and I couldn't find any solution to this.

Any help is highly appreciated. Thanks.

1st December, 2016

IamCrazyD left a reply on Laravel 5 Password Reset Not Working • 11 months ago

@yansusanto That is strange.. In my Laravel 5.3.* app, I have in the User model:

public function setPasswordAttribute($password)
{   
    $this->attributes['password'] = bcrypt($password);
}

I just tried to change the password, and re-logging in. It is completely working fine without any issue, on my end, at least.

Can you please show me the code of resetting the password.

29th October, 2016

IamCrazyD started a new conversation Props Values Not Rendering In Vuejs • 1 year ago

I am trying to create an ajax form component in vuejs in Laravel 5.3 application. But, I guess, I have stuck in displaying the form fields. Can anybody help me out?

The front end to render the form:

<ajax-form
    :autocomplete=false
    :schema="[{
        label: 'Username:',
        type: 'text',
        id: 'username',
        name: 'username',
        placeholder: 'Eg. johndoe',
        inputClass: 'input is-info',
        model: 'username',
        required: true,
    }, {
        label: 'Email:',
        type: 'email',
        id: 'email',
        name: 'email',
        placeholder: 'Eg. [email protected]',
        inputClass: 'input is-info',
        model: 'email',
        required: true,
    }, {
        label: 'Password',
        type: 'password',
        id: 'password',
        name: 'password',
        placeholder: 'Eg. password',
        inputClass: 'input is-info',
        model: 'password',
        required: true,
    }, {
        label: 'Confirm Password',
        type: 'password',
        id: 'confirm_password',
        name: 'confirm_password',
        placeholder: 'Eg. password',
        inputClass: 'input is-info',
        model: 'confirm_password',
        required: true,
    }]"
></ajax-form>

And the template in AjaxForm.vue file:

<form method="POST">
    <div v-for="field in schema">
        <label class="label">{{ field.label }}</label>
        <p class="control">
            <input
                type="field.type"
                name="field.name"
                id="field.id"
                class="field.inputClass"
                placeholder="field.placeholder"
                required="field.required"
                v-model="field.model"
            >
        </p>
    </div>
</form>

And the content of the script tag:

<script>
    export default {
        props: {
            autocomplete: Boolean,
            schema: Array
        }
    }
</script>

The above code is not rendering the html correctly. I mean, the classes are not getting added. I don't know what is the mistake that I have made.. Kindly help me out..

P.S.: I have just started learning about the components, so, this might a silly mistake. But, any kind of help is highly appreciated.

Thank you.

24th September, 2016

IamCrazyD started a new conversation Bind Database Table Values Inside A Modal Vue Component Form • 1 year ago

In my Laravel 5.3 application, I am having a modal component which gets displayed when a user clicks on a button to edit the data.

Loading of modal window is done with the following code:

<a
    href="#"
    class="btn btn-sm btn-info"
    data-toggle="modal"
    data-target="#editCountryModal"
    data-country-id="{{ countries['id'] }}"
    data-country-code="{{ countries['code'] }}"
    data-country-name="{{ countries['name'] }}"
    data-country-currency-code="{{ countries['currency_code'] }}"
    data-country-currency-name="{{ countries['currency_name'] }}"
    data-country-display="{{ countries['display'] }}"
>
    <i class="fa fa-lg fa-pencil"></i>
</a>

The above code loads the following form which is inside a modal component.

<template>
    <div class="errors"></div>

    <form method="POST" @submit.prevent="updateCountry">
        <div class="form-group">
            <label for="name">Id:</label>
            <input
                type="text"
                name="id"
                id="countryId"
                class="inputText"
                autofocus="autofocus"
                placeholder="1"
                readonly="readonly"
                v-model="formData.countryId"
            />
        </div>

        <div class="form-group">
            <label for="name">Name:</label>
            <input
                type="text"
                name="name"
                id="name"
                class="inputText"
                placeholder="Eg. India"
                required="required"
                v-model="formData.name"
            />
            <div class="error">
                <span v-if="formErrors['name']" 
                      class="text-danger"
                >
                      {{ formErrors['name'] }}
                </span>
            </div>
        </div>

        <div class="form-group">
            <label for="code">Code:</label>
            <input
                type="text"
                name="code"
                id="code"
                class="inputText"
                placeholder="Eg. IND"
                required="required"
                v-model="formData.code"
            />
            <div class="error">
                <span v-if="formErrors['code']"
                      class="text-danger"
                >
                    {{ formErrors['code'] }}
                </span>
            </div>
        </div>

        <div class="form-group">
            <label for="currency_name">Currency Name:</label>
            <input
                type="text"
                name="currency_name"
                id="currency_name"
                class="inputText"
                placeholder="Eg. Indian National Rupee"
                required="required"
                v-model="formData.currency_name"
            />
            <div class="error">
                <span v-if="formErrors['currency_name']"
                      class="text-danger"
                >
                    {{ formErrors['currency_name'] }}
                </span>
            </div>
        </div>

        <div class="form-group">
            <label for="currency_code">Currency Code:</label>
            <input
                type="text"
                name="currency_code"
                id="currency_code"
                class="inputText"
                placeholder="Eg. INR"
                required="required"
                v-model="formData.currency_code"
            />
            <div class="error">
                <span v-if="formErrors['currency_code']"
                      class="text-danger"
                >
                    {{ formErrors['currency_code'] }}
                </span>
            </div>
        </div>

        <div class="form-group">
            <label for="display">Display:</label>
            <select name="display"
                    id="display" 
                    class="selectText" 
                    required="required" 
                    v-model="formData.display"
            >
                <option value="Disabled" selected="selected">Disabled</option>
                <option value="Enabled">Enabled</option>
            </select>
            <div class="error">
                <span v-if="formErrors['display']"
                      class="text-danger"
                >
                    {{ formErrors['display'] }}
                </span>
            </div>
        </div>

        <button type="submit" class="button button--teal">Edit</button>
    </form>
</template>
<script>
    export default {
        data() {
            return {
                formData: {
                    countryId: '',
                    name: '',
                    code: '',
                    currency_name: '',
                    currency_code: '',
                    display: ''
                },
                formErrors: {},
                allCountries: []
            }
        },

        ready: function() {
            this.fetchAllCountries();
        },

        methods: {
            notify: function(mType, mTitle, mMessage, nDelay) {
                $.iGrowl({
                    type: mType == 'success' ? 'success' : 'error',
                    title: mTitle,
                    message: mMessage,
                    icon: mType == 'success' ? 'steadysets-checkmark !' : 'feather-cross',
                    delay: nDelay,
                    animShow: 'bounceInRight',
                    animHide: 'bounceOutRight'
                });
            },

            fetchAllCountries: function() {
                $.get('/api/all-countries', function(countries) {
                    this.allCountries = countries;
                }.bind(this), 'json');
            },

            updateCountry: function(e) {
                $('.button').addClass('button--disabled')
                            .html('<i class="fa fa-spinner fa-spin"></i> Editing...');
                $(document).find('i.fa.fa-spinner.fa-spin').show();

                this.$http
                    .post('/admin/settings/update-country/' + this.formData.countryId, this.formData)
                    .then((result) => {
                        var res = result.data;

                        $('.button').removeClass('button--disabled').html('Edit');
                        $(document).find('i.fa.fa-spinner.fa-spin').hide();

                        // 3000 is the number of seconds before disappearing
                        this.notify(res.status, res.title, res.message, 3000);
                    },
                    (err) => {
                        $('.button').removeClass('button--disabled').html('Edit');
                        $(document).find('i.fa.fa-spinner.fa-spin').hide();

                        if ( err.status === 422 ) {
                            var errors = err.data;
                            this.formErrors = errors;

                        }
                });

                return false;
            }
        }
    }
</script>

What is happening is, whenever I submit the above form, it gets submitted with no values at all. Meaning I get an empty string for all the fields above. But, if I go to each field manually, it gets submitted with proper field values.

I want that whenever a user just clicks on the submit button, the values should get updated. Meaning the user should not be forced to click on every field, so that vue can recognize it.

**Bottom line question:**How do I submit the default values (loaded in the modal window) of the form if the user just clicks on the submit button ?

Any help is highly appreciated. Thanks.

3rd September, 2016

IamCrazyD started a new conversation Pusher Not Displaying The Message In Laravel 5.3 • 1 year ago

I am new to Pusher and Laravel Echo and learning it step by step. I am trying to implement it in my new project but somehow, I am unable to understand how this pusher library works with Laravel Echo.

What I am doing is, on administrator registration, I just want to check that whether what I have done is correct or not. I simply want to see what is the output of the event that I generated, on the debug console in my pusher dashboard account.

I have created an event AdministratorGenerated with the follwing contents:

class AdministratorGenerated implements ShouldBroadcast
{
    use InteractsWithSockets, SerializesModels;

    public $user;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('administrator');
    }
}

In bootstrap.js file, I have:

import Echo from "laravel-echo"

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'my-pusher-key',
    cluster: 'ap1',
    encrypted: true
});

window.Echo.channel('administrator')
    .listen('AdministratorGenerated', (e) => {
        console.log(e);
    });

On successfully registering the form, I am firing an event

event(new AdministratorGenerated($registeredUser));

This event will fire the welcome email and sets up the default accounts.

But, when I go to debug console in Pusher dashboard, all I get to see is the following:

pusher image

Can anybody help me out with this ?

Thanks in advance.

30th June, 2016

IamCrazyD left a reply on Get All Inputs In Form With Vuejs • 1 year ago

Can you please share the code for :data=data binding ?

29th June, 2016

IamCrazyD started a new conversation Submit Form Using VueJs And AJAX In Laravel 5.1 • 1 year ago

I am trying to submit a form using AJAX and VueJs. But somehow I am failing to achieve that. I always end up getting an empty Illuminate\Http\Request object.

The blade file:

<body>
    <div class="container">
        <generate-admin></generate-admin>
    </div>

    <script src="https:http://code.jquery.com/jquery.js"></script>
    <script src="{{ url('/js/main.js') }}"></script>
</body>

The component:

<template>
    <form id="createAdministrator" @submit.prevent="createAdministrator">

        <div class="form-group">

           <input type="text"
                  name="username"
                  id="txtUserName"
                  placeholder="Username"
                  autocomplete="off"
                  v-model="username"
           />

        </div>

        <input type="submit" value="Submit">

    </form>
</template>

<script>
    export default {
        data: function() {
            return {
                username: ''
            }
        },

        methods: {
            createAdministrator: function() {
                formContents = jQuery("#createAdministrator").serialize();

                this.$http.post('/admin', formContents).then(function(response, status, request) {
                    console.log(response);
                }, function() {
                    console.log('failed');
                });
            }
        }
    }
</script>

main.js file

import Vue from 'vue';
import GenerateAdmin from './components/GenerateAdmin.vue';

var VueResource = require('vue-resource')
Vue.use(VueResource);

Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('content');
Vue.http.options.emulateJSON = true;

new Vue({
    el: 'body',

    components: { GenerateAdmin }
});

routes.php

Route::get('/admin/create', function () {
    return view('admin.create');
});

Route::post('/admin', function(Request $request) {
    // returns an empty object.
    return response(['results' => $request]);
});

Route::get('/', function () {
    return view('welcome');
});

What I get in return is:

"{"results":{"attributes":{},"request":{},"query":{},"server":{},"files":{},"cookies":{},"headers":{}}}"

When I check the Request Payload section of Network Tab in Chrome.. I do see that the form is getting submitted successfully with whatever data I write in the text box above.

Why is this happening ? Kindly guide me where I have made the mistake ?

P.S.: I have started learning VueJs Components recently.

4th June, 2016

IamCrazyD started a new conversation Manual Pagination In Laravel 5.1 • 1 year ago

How to create a manual pagination in Laravel 5.1 ?

I have an array of results (more than 25 result) fetched from the database. I am trying to implement Laravel Pagination in my application.

What I want is paginate the results fetched.

What I get is pagination of the same results.

The code that I have used so far:

<?php
$productsInParent = $category->products;
$productsInParentCategory = new Illuminate\Support\Collection;
$allProducts = $allProductsFromChild = [];

foreach($productsInParent as $prodInParent) {
    $allProducts[] = $prodInParent;
}

foreach($category->childs as $child) {
    foreach($child->products as $productsInChildren) {
        $allProductsFromChild[] = $productsInChildren;
    }
}

$fetchAllProducts = array_merge($allProducts, $allProductsFromChild);

$result = array_slice($fetchAllProducts, 0, 12);

$paginateResults = new Illuminate\Pagination\LengthAwarePaginator($result, count($fetchAllProducts), 12);
?>

I do get the pagination, but when working inspecting, on page 2, on page 3, and so on.. I get the result that is visible on page 1 of the pagination on all the subsequent pages of the pagination.

Kindly help me out with this. Any help is highly appreciated.

P.S.: I am trying to learn on my own how to integrate custom pagination in Laravel 5.1

7th April, 2016

IamCrazyD left a reply on Display Array Values In Table Format In Laravel 5.1 • 1 year ago

@JoeriAben I cannot use that because it's a normal multi-dimensional array.. Still, I appreciate your reply and help..

IamCrazyD started a new conversation Display Array Values In Table Format In Laravel 5.1 • 1 year ago

I have an array like so:

array:55 [▼
  0 => array:13 [▼
    "product_id" => "1"
    "name" => "Glowing Antique Multi-Color Necklace And Hangings"
    "product_code" => "DIV-COL-0001-0001"
    "option_code" => ""
    "net_price" => "693.00"
    "format" => "Single"
    "page_url" => "category/5/jewellery/DIV-COL-0001-0001/glowing-antique-multi-color-necklace-and-hangings"
    "image" => "http://localhost:8000/images/products/uploads/dc-0001-0001-75-75.jpg"
    "sellerCommission" => "450.00"
    "moderatorCommission" => "14.00"
    "principalModeratorCommission" => "17.00"
    "affiliateCommission" => "28.00"
    "accountType" => "affiliate"
  ]
  25 => array:13 [▼
    "product_id" => "24"
    "name" => "Blue Colored Cotton Zip Pouch (3 Nos.)"
    "product_code" => "PRA-KEN-0002-0006"
    "option_code" => ""
    "net_price" => "184.62"
    "format" => "Single"
    "page_url" => "category/11/bags-and-purses-women/PRA-KEN-0002-0006/blue-colored-cotton-zip-pouch-3-nos"
    "image" => "http://localhost:8000/images/products/uploads/pk-0002-0006-75-75.jpg"
    "sellerCommission" => "120.00"
    "moderatorCommission" => "4.00"
    "principalModeratorCommission" => "5.00"
    "affiliateCommission" => "7.00"
    "accountType" => "affiliate"
  ]
  26 => array:13 [▼
    "product_id" => "25"
    "name" => "Side Hanging Purse (2 Nos.)"
    "product_code" => "PRA-KEN-0002-0007"
    "option_code" => ""
    "net_price" => "184.62"
    "format" => "Single"
    "page_url" => "category/11/bags-and-purses-women/PRA-KEN-0002-0007/side-hanging-purse-2-nos"
    "image" => "http://localhost:8000/images/products/uploads/pk-0002-0007-75-75.jpg"
    "sellerCommission" => "120.00"
    "moderatorCommission" => "4.00"
    "principalModeratorCommission" => "5.00"
    "affiliateCommission" => "7.00"
    "accountType" => "affiliate"
 ]
  44 => array:13 [▼
    "product_id" => "24"
    "name" => "Blue Colored Cotton Zip Pouch (3 Nos.)"
    "product_code" => "PRA-KEN-0002-0006"
    "option_code" => ""
    "net_price" => "184.62"
    "format" => "Single"
    "page_url" => "category/11/bags-and-purses-women/PRA-KEN-0002-0006/blue-colored-cotton-zip-pouch-3-nos"
    "image" => "http://localhost:8000/images/products/uploads/pk-0002-0006-75-75.jpg"
    "sellerCommission" => "120.00"
    "moderatorCommission" => "4.00"
    "principalModeratorCommission" => "5.00"
    "affiliateCommission" => "7.00"
    "accountType" => "principal_moderator"
  ]
  // And the list continues ...
]

The code that I have tried so far, works correctly to a certain extent.

<tr>
    <th style="vertical-align: top;">Id</th>
    <th style="vertical-align: top;">Details</th>
    <th style="vertical-align: top;">Net Price</th>
    <th style="vertical-align: top;">Invoicer<br /> Commission</th>
    <th style="vertical-align: top;">Moderator Commission</th>
    <th style="vertical-align: top;">Principal Moderator Commission</th>
    <th style="vertical-align: top;">Affiliate Commission</th>
</tr>

@foreach($products as $product)
    <tr>
        <td>{{ $product['product_id'] }}</td>
        <td>
            <img src="{{ $product['image'] }}" alt="{{ $product['name'] }}" class="pull-left" style="margin-right: 15px">
            <a href="{{ $product['page_url'] }}" class="links-dark">{{ $product['name'] }}</a><br />
            Product Code: {{ $product['product_code'] }}<br />
            @if($product['option_code'] !== '')
                Option Code: {{ $product['option_code'] }}
            @endif
        </td>
        <td class="text-right">{{ $product['net_price'] }}</td>

        @if($product['accountType'] === 'seller')
            <td class="text-right">{{ number_format($product['sellerCommission'], 2) }}</td>
        @else
            <td class="text-right">--</td>
        @endif

        @if($product['accountType'] === 'moderator')
            <td class="text-right">{{ number_format($product['moderatorCommission'], 2) }}</td>
        @else
            <td class="text-right">--</td>
        @endif

        @if($product['accountType'] === 'principal_moderator')
            <td class="text-right">{{ number_format($product['principalModeratorCommission'], 2) }}</td>
        @else
            <td class="text-right">--</td>
        @endif

        @if($product['accountType'] === 'affiliate')
            <td class="text-right">{{ number_format($product['affiliateCommission'], 2) }}</td>
        @else
            <td class="text-right">--</td>
        @endif
    </tr>
@endforeach

The above code works, but it adds a new row to the table which is what I am not looking for. I do not want to add a new row, instead I would like to display the required data in that row only.

Meaning, for the product_id = 24, there are 2 accountType attached viz., affiliate and principal_moderator. I would like to populate a single row with that data instead of 2 different rows.

How do I achieve it ??

I know this must be far easy, but I have failed to solve it, because I am still at the learning stage.

Any help is highly appreciated. Thanks.

P.S.: All the values are coming from the database, and the number of child arrays can be infinite.

28th March, 2016

IamCrazyD started a new conversation Laravel GroupBy Using Database Table Column Values • 1 year ago

I am having the following table structure in my database table:

+---------+----------------+--------------------------------+---------------------+
| user_id | payable_amount | payment_type                   | created_at          |
+---------+----------------+--------------------------------+---------------------+
|      10 |         450.00 | order_payment                  | 2016-03-28 08:21:14 |
|       3 |          14.00 | moderator_commission           | 2016-03-28 08:21:14 |
|      10 |          17.00 | principal_moderator_commission | 2016-03-28 08:21:14 |
|       4 |          28.00 | affiliate_commission           | 2016-03-28 08:21:14 |
|      10 |         700.00 | order_payment                  | 2016-03-28 08:21:14 |
|       3 |          22.00 | moderator_commission           | 2016-03-28 08:21:15 |
|      10 |          26.00 | principal_moderator_commission | 2016-03-28 08:21:15 |
|       4 |          44.00 | affiliate_commission           | 2016-03-28 08:21:15 |
|      10 |          75.00 | shipping                       | 2016-03-28 08:21:17 |
|       8 |          75.00 | shipping                       | 2016-03-28 08:21:17 |
|      11 |         150.00 | shipping                       | 2016-03-28 08:21:17 |
|       7 |          75.00 | shipping                       | 2016-03-28 08:21:17 |
|      10 |         500.00 | deduction                      | 2016-03-28 09:59:22 |
|      10 |         200.00 | deduction                      | 2016-03-28 10:46:39 |
|      10 |        2500.00 | credit                         | 2016-03-28 10:54:32 |
+---------+----------------+--------------------------------+---------------------+

What I am trying to do is I want to display the above in tabular format only but by grouping the column payment_type NOT HAVING the value of deduction, credit of the same user_id.

Output should be like this:

+---------+----------------+--------------------------------+---------------------+
| user_id | payable_amount | payment_type                   | created_at          |
+---------+----------------+--------------------------------+---------------------+
|      10 |        1150.00 | order_payment                  | 2016-03-28 08:21:14 |
|       3 |          36.00 | moderator_commission           | 2016-03-28 08:21:14 |
|      10 |          43.00 | principal_moderator_commission | 2016-03-28 08:21:14 |
|       4 |          72.00 | affiliate_commission           | 2016-03-28 08:21:14 |
       10 |          75.00 | shipping                       | 2016-03-28 08:21:17 |
|       8 |          75.00 | shipping                       | 2016-03-28 08:21:17 |
|      11 |         150.00 | shipping                       | 2016-03-28 08:21:17 |
|       7 |          75.00 | shipping                       | 2016-03-28 08:21:17 |
|      10 |         500.00 | deduction                      | 2016-03-28 09:59:22 |
|      10 |         200.00 | deduction                      | 2016-03-28 10:46:39 |
|      10 |        2500.00 | credit                         | 2016-03-28 10:54:32 |
+---------+----------------+--------------------------------+---------------------+

The code that I have tried so far: Controller:

public function fetchUser($userCode)
{
    $member = User::where('code', $userCode)->first();

    $allOrderUserPayments = OrderUserPayment::where('user_id', $member->id)
                            ->groupBy('payment_type')->get();

    return view('admin.orders.payments.user', compact('allOrderUserPayments'));
}

View:

<tr>
     <th>Details</th>
     <th>Total Wt</th>
     <th>Pay Wt</th>
     <th>Non - Pay Wt</th>
     <th>Total Amt</th>
     <th>Pay Amt</th>
     <th>Non - Pay Amt</th>
     <th>Credit</th>
     <th>Deduction</th>
     <th>Payment</th>
     <th>Balance</th>
     <th>Notes</th>
     <th>Created At</th>
</tr>
@foreach($allOrderUserPayments as $key => $order)
    <?php $credits = $balance = 0.00; ?>

    @if($order->payment_type === 'order_payment')
        <?php
        $totalOrderPaymentAmount = 0.00;
        $ordersOrderPayment = App\OrderUserPayment::where('order_code', $order->order_code)
                  ->where('user_id', $order->user_id)
                  ->where('payment_type', 'order_payment')
                  ->selectRaw('*, SUM(payable_amount) AS totalAmount')
                  ->first();

        $ordersPayableAmount = App\OrderUserPayment::where('order_code', $order->order_code)
                  ->where('user_id', $order->user_id)
                  ->where('payment_type', 'order_payment')
                  ->where('payment_payability_status', '!=', 'Non-Payable')
                  ->selectRaw('*, SUM(payable_amount) AS totalPayableAmount')
                  ->first();
         ?>
         <tr>
             <td>{{ $order->order_code }} / Order Payment</td>
             <td></td>
             <td></td>
             <td></td>
             <td>{{ $ordersOrderPayment->totalAmount }}</td>
             <td>{{ $ordersPayableAmount->totalPayableAmount }}</td>
             <td>{{ number_format($ordersOrderPayment->totalAmount - $ordersPayableAmount->totalPayableAmount, 2) }}</td>
             <td>{{ $ordersOrderPayment->totalAmount }}</td>
             <td></td>
             <td></td>
             <td>{{ $totalCredits += $ordersOrderPayment->totalAmount }}</td>
             <td></td>
             <td></td>
         </tr>
     @endif

     @if($order->payment_type === 'shipping')
         <?php
         $invoicer = App\OrderInvoicerShipping::where('invoicer_id', $order->user_id)->where('order_code', $order->order_code)->first();
         ?>
         <tr>
             <td>{{ $order->order_code }} / Shipping</td>
             <td>{{ $invoicer !== null ? $invoicer->weight : '' }}</td>
             <td></td>
             <td></td>
             <td>{{ $order->payable_amount }}</td>
             <td>{{ $order->payable_amount }}</td>
             <td></td>
             <td><?php $totalCredits += ($credits += $order->payable_amount); ?>{{ $credits = $order->payable_amount }}</td>
             <td></td>
             <td></td>
             @if($order->payment_payability_status !== 'Non-Payable')
                 <td>{{ $balance += $totalCredits }}</td>
             @else
                 <td></td>
             @endif
             <td></td>
             <td>{{ $order->payment_updated_at !== null ? $order->payment_updated_at->timezone('Asia/Kolkata') : '' }}</td>
         </tr>
     @endif

     @if($order->payment_type === 'principal_moderator_commission')
         <?php
         $ordersOrderPaymentPM = App\OrderUserPayment::where('order_code', $order->order_code)
                  ->where('user_id', $order->user_id)
                  ->where('payment_type', 'principal_moderator_commission')
                  ->selectRaw('*, SUM(payable_amount) AS totalAmount')
                  ->first();

          $ordersPayableAmountPM = App\OrderUserPayment::where('order_code', $order->order_code)
                  ->where('user_id', $order->user_id)
                  ->where('payment_type', 'principal_moderator_commission')
                  ->where('payment_payability_status', '!=', 'Non-Payable')
                  ->selectRaw('*, SUM(payable_amount) AS totalPayableAmount')
                  ->first();
           ?>
           <tr>
               <td>{{ $order->order_code }} / Principal Moderator</td>
               <td></td>
               <td></td>
               <td></td>
               <td>{{ $ordersOrderPaymentPM->totalAmount }}</td>
               <td>{{ $ordersPayableAmountPM->totalPayableAmount }}</td>
               <td>{{ number_format($ordersOrderPaymentPM->totalAmount - $ordersPayableAmountPM->totalPayableAmount, 2) }}</td>
               <td>{{ $ordersOrderPaymentPM->totalAmount }}</td>
               <td></td>
               <td></td>
               <td>{{ $totalCredits += $ordersOrderPaymentPM->totalAmount }}</td>
               <td></td>
               <td></td>
           </tr>
       @endif

       @if($order->payment_type === 'deduction')
           <tr>
              <td>Deduction</td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td>{{ $order->payable_amount }}</td>
              <td></td>
              <td>{{ $totalCredits -= $order->payable_amount }}</td>
              <td></td>
              <td></td>
           </tr>
       @elseif($order->payment_type === 'credit')
           <tr>
               <td>Credit</td>
               <td></td>
               <td></td>
               <td></td>
               <td></td>
               <td></td>
               <td></td>
               <td>{{ $order->payable_amount }}</td>
               <td></td>
               <td></td>
               <td>{{ $totalCredits += $order->payable_amount }}</td>
               <td></td>
               <td></td>
           </tr>
       @endif
   @endforeach

How do I achieve this ?

P.S.: I know the above code is not the correct way to do fetch the desired result. I am still at the learning stage and I need some help. Kindly help me out in achieving this.

Any help is highly appreciated. Thank You.

26th March, 2016

IamCrazyD started a new conversation Calculation Of Values From Different Database Tables In Laravel • 1 year ago

I have 4 tables with timestamps of laravel:

orders - order_code, user_id, invoicer_id, moderator_id, affiliate_id, payable_amount, product_id order_invoicer_shippings - orer_code, invoicer_id, shipping_weight, shipping_amount order_commissions - order_code, moderator_id, affiliate_id, moderator_commission_amount, affiliate_commission_amount order_payments - order_code, invoicer_id, moderator_id, affiliate_id, credit, deductions, payments

Scenario: On placing the order, order details are inserted in the orders table, shipping details are inserted in the order_invoicer_shippings table. Also the commissions on the orders and/or products are inserted in the order_commissions_table. Now admin decides to pay them (affiliate, moderator) their dues (shipping amount, commissions), for that he wants to know the balance of each user.

I want to show table data in descending order of created_at field. It should be displayed in the descending order of the event that is happening, irrespective of the order placed and/or task done by the admin.

Along with this, there is a calculation that should happen. Calculation of the current balance of the user (affiliate, moderator).

Formula for calculating the current balance is:

Available Balance + Credit - Deductions - Payments

Example: order_invoicers_table contains:

invoicer_id    shipping_weight    shipping_amount        created_at
    1                                50                                  100                      2016-03-18 03:05:32
    2                                75                                  150                      2016-03-20 11:50:05
    1                              150                                  300                     2016-03-25 06:35:30

order_commissions_table contains:

moderator_id    moderator_comm_amount    affiliate_id    affiliate_comm_amount         created_at
    1                                               150                                       5                                   200                            2016-03-18 03:05:32
    9                                               350                                       4                                   225                            2016-03-20 11:50:05
    6                                               300                                       3                                   205                            2016-03-25 06:35:30

Now in admin, it should be like this for user_id: 1:

details             payable_amt    credits    deductions    payments    balance        created_at
shipping              200                       200                0                       0                  200           2016-03-18 03:05:32
mod_comm       150                       150                0                       0                  350           2016-03-18 03:05:32

Admin now decides to pay the above user (id: 1) the shipping amount (Desired Output):

details              payable_amt    credits    deductions    payments    balance        created_at
payment                                                                                          200                 150          2016-03-24 08:08:10
mod_comm      150                          150                0                    0                    350          2016-03-18 03:05:32
shipping              200                         200                0                     0                   200           2016-03-18 03:05:32

The payments/credits/deductions gets inserted in the order_payments table.

The code that I have tried so far is: Controller:

public function fetchUser($userCode)
{
    $member = User::where('code', $userCode)->first();

    $accountTypes = $member->getAllAccountTypes();

    $invoicerOrders = $moderatorOrders = $affiliateOrders = null;

    foreach($accountTypes as $key => $account) {
        if($account->type === 'invoicer') {
            $invoicerOrders = Order::with('invoicerShippings')
                          ->where('invoicer_id', $account->pivot->user_id)
                          ->latest()->groupBy('code')->get();
        }

        if($account->type === 'moderator') {
            $moderatorOrders = Order::where('moderator_id', $account->pivot->user_id)
                           ->latest()->groupBy('code')->get();
        }

        if($account->type === 'affiliate') {
            $affiliateOrders = Order::where('affiliate_id', $account->pivot->user_id)
                           ->latest()->groupBy('code')->get();
        }
    }

    $allOrders = [
        'invoicerOrders'           => $invoicerOrders,
        'principalModeratorOrders' => $principalModeratorOrders,
        'affiliateOrders'          => $affiliateOrders,
   ];

    return view('admin.orders.payments.user', compact('allOrders', 'member'));
}

View File:

<?php
$totalPayableWeight = $totalNonPayableWeight = $payableWeight = $nonPayableWeight = 0;
$totalPayableAmount = $totalNonPayableAmount = $payableAmount = $nonPayableAmount = 0;
$totalPayableCommissionAmount = $totalNonPayableCommissionAmount = $payableCommissionAmount = $nonPayableCommissionAmount = 0;
$totalBalance = 0;
?>
@if($allOrders['invoicerOrders'] !== null)

    @foreach($allOrders['invoicerOrders'] as $key => $order)
        <?php
        $tempInvPayOrder = App\OrderCommission::where('invoicer_id', $member->id)
                           ->orderBy('created_at', 'DESC')->get();
        $balance = 0;

        foreach($tempInvPayOrder as $ord) {
           $o = App\Order::find($ord->order_id);
           if($o->product_payability !== 'Non-Payable') {
               $payableCommissionAmount = $ord->seller_total_commission_amount;
               $totalPayableCommissionAmount += $payableCommissionAmount;
           }

           if($o->product_payability === 'Non-Payable') {
               $nonPayableCommissionAmount = $ord->seller_total_commission_amount;
               $totalNonPayableCommissionAmount += $nonPayableCommissionAmount;
           }
       }
   ?>
   <tr>
       <td>{{ $order->code }} / Invoicer Shipping</td>
       <td>{{ $totalPayableCommissionAmount + $totalNonPayableCommissionAmount }}</td>
       <td>{{ $totalPayableCommissionAmount }}</td>
       <td>{{ $totalNonPayableCommissionAmount }}</td>
       <td>{{ $totalPayableCommissionAmount }}</td>
       <td>
           <?php
           $balance += $totalPayableCommissionAmount;
           $invoicerTotalPaymentBalance += $balance;
           ?>
           {{ $totalBalance = $invoicerTotalPaymentBalance }}
       </td>
       <td>
           {{ App\OrderCommission::where('invoicer_id', $member->id)->where('order_code', $order->code)->first()->created_at }}
       </td>
   </tr>
@endforeach


<?php
$moderatorTotalPayableCommissionAmount = $moderatorTotalNonPayableCommissionAmount = $moderatorPayableCommissionAmount = $moderaotrNonPayableCommissionAmount = 0;
 ?>
 @if($allOrders['moderatorOrders'] !== null && ! $allOrders['moderatorOrders']->isEmpty())
     @foreach($allOrders['moderatorOrders'] as $key => $order)
         <?php
         $tempOrderCommissions = App\OrderCommission::where('moderator_id', $member->id)->latest()->get();

         foreach($tempOrderCommissions as $ord) {
             $o = App\Order::find($ord->order_id);
             if($o->product_payability !== 'Non-Payable') {
                 $moderatorPayableCommissionAmount = $ord->moderator_total_commission_amount;
                 $moderatorTotalPayableCommissionAmount += $moderatorPayableCommissionAmount;
             }

             if($o->product_payability === 'Non-Payable') {
                 $moderaotrNonPayableCommissionAmount = $ord->moderator_total_commission_amount;
                 $moderatorTotalNonPayableCommissionAmount += $moderaotrNonPayableCommissionAmount;
             }
        }
        ?>
        <tr>
            <td>{{ $order->code }} / Moderator Commission</td>
            <td>{{ $moderatorTotalPayableCommissionAmount + $moderatorTotalNonPayableCommissionAmount }}</td>
            <td>{{ $moderatorTotalPayableCommissionAmount }}</td>
            <td>{{ $moderatorTotalNonPayableCommissionAmount }}</td>
            <td>{{ $moderatorTotalPayableCommissionAmount }}</td>
            <td>{{ $tempOrderCommissions->first()->created_at }}</td>
        </tr>
    @endforeach
@endif

Sorry for such a long question, but I had to give the detailed info in order to solve the issue.

Any help is highly appreciated.

7th December, 2015

IamCrazyD started a new conversation Form Sending Mail Thrice In Laravel 5 • 1 year ago

I have this weird issue that I have never came across before ever since I started learning laravel.

I have a contact form:

{!! Form::open(['url' => '/contact-form', 'id' => 'formContact']) !!}
    <div class="col-md-12 col-sm-12 form-group">
        {!! Form::label('full_name', 'Full Name:', ['class' => 'fw_400']) !!}
        {!! Form::text('full_name', null, ['class' => 'form-control input-sm']) !!}
    </div>

    <div class="col-md-6 col-sm-6 form-group">
        {!! Form::label('email', 'Email:', ['class' => 'fw_400']) !!}
        {!! Form::text('email', null, ['class' => 'form-control input-sm']) !!}
    </div>

    <div class="col-md-6 col-sm-6 form-group">
        {!! Form::label('contact', 'Contact Number:', ['class' => 'fw_400']) !!}
        {!! Form::text('contact', null, ['class' => 'form-control input-sm']) !!}
    </div>


    <div class="col-md-12 col-sm-12 form-group">
        {!! Form::label('contact_message', 'Contact Message:', ['class' => 'fw_400']) !!}
        {!! Form::textarea('contact_message', null, ['class' => 'form-control input-sm', 'rows' => 5]) !!}
    </div>

    <div class="col-md-12 col-sm-12 form-group">
        {!! Form::submit('Submit', ['class' => 'btn btn-primary btn-block btnContactOnContactPage']) !!}
    </div>
{!! Form::close() !!}

When I click on the submit button, AJAX call is made.. Here's the ajax handler:

(function() {
    $('#formContact').submit(function(e) {

        $('.btnContactOnContactPage').prop('disabled', true);

        var inputData = $('#formContact').serialize();

        $.ajax({
            url: $('#formContact').attr('action'),
            type: 'POST',
            data: inputData,
            success: function(m) {
                $('.btnContactOnContactPage').prop('disabled', false);

                if (m.status === 'success') {
                    toastr.success(m.msg);

                    setTimeout(function() {
                        window.location.reload();
                    }, 3000)
                }
            },
            error: function(e) {
                if (e.status === 422) {

                    $('.btnContactOnContactPage').prop('disabled', false);

                    var errors = e.responseJSON;

                    var errorsHtml = '<div class="alert alert-danger"><ul>';
                    errorsHtml += '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
                    $.each(errors, function(key, value) {
                        errorsHtml += '<li class="text-danger">' + value[0] + '</li>';
                    });
                    errorsHtml += '</ul></div>';
                    $('.errors').html(errorsHtml);
                }
            }
        });

        return false;
    });
})();

And the controller method:

public function postContact(Request $request)
{
    $this->validate($request, [
        'full_name'       => 'required',
        'email'           => 'required|email',
        'contact'         => 'required|regex:/^[0-9+\-]+$/',
        'contact_message' => 'required'
    ]);

    if ($request->ajax()) {
        $prevContactCode = DB::table('contact_messages')->latest()->limit(1)->pluck('cont_code');
        if ($prevContactCode == "" || empty($prevContactCode)) {
            $request['cont_code'] = 'CON-000001';
        }
        else {
            $request['cont_code'] = ++$prevContactCode;
        }

        $contactMessage = ContactMessage::create($request->all());

        $dataToMail = [
            'cont_code'       => $contactMessage->cont_code,
            'full_name'       => $contactMessage->full_name,
            'email'           => $contactMessage->email,
            'contact'         => $contactMessage->contact,
            'contact_message' => $contactMessage->contact_message
        ];

        $mail = Mail::send('emails.contact', $dataToMail, function ($message) use($dataToMail)
        {
            $message->from($dataToMail['email'], $dataToMail['full_name']);
            $message->to('contact@example.com', 'Example Contact')
                    ->subject('Contact Form Details from example.com (Form No.:' . $dataToMail['cont_code'] . ')')
                    ->cc(['ex@example.net', 'exam@hotmail.com'])
                    ->bcc(['examp@gmail.com', 'esmap@example.net']);
        });

        var_dump($mail); // displays **int 5** in chrome console

        dd($mail); // displays **5** in chrome console

        if ($mail) {
            return response(['status' => 'success', 'msg' => 'Contact form details has been successfully submitted.']);
        }
    }

    return response(['status' => 'failed', 'msg' => 'Something went wrong. Please try again later.']);
}

The issue is that, the mail is sent thrice instead of just once. I don't know what is happening here. Earlier [maybe 5 months back], it was working correctly, and now, all of a sudden, it started doing this. I am trying to figure out what is the reason behind this, but to no success. I have also updated the framework using composer update but the issue still exists.

Where I have made the mistake ? Kindly help me out.

9th September, 2015

IamCrazyD left a reply on Maximum Function Nesting Level Of '100' Reached, Aborting Laravel 5.1 • 2 years ago

@No maD Don't you think that I'll have to add that code again and again to every blade file whenever required ? What I did is I replace the **xdebug.max_nesting_level=100** with **xdebug.max_nesting_level=500**, and the error exception was gone.

7th September, 2015

IamCrazyD left a reply on Maximum Function Nesting Level Of '100' Reached, Aborting Laravel 5.1 • 2 years ago

@NomaD why you are suggesting me to use option 2 of your own solution ? May I know the reason ??

IamCrazyD left a reply on Maximum Function Nesting Level Of '100' Reached, Aborting Laravel 5.1 • 2 years ago

@bobbybouwmann I am failing to update the php.ini file. The loaded configuration file is /etc/php5/apache2/php.ini.. So as you said, I added the **xdebug.max_nesting_level=500** in the last line and restarted the apache server with the following command in the terminal:

sudo service apache2 restart

It did restarted, but when checked the phpinfo() in the browser, it still showed 100 only. What could be the issue ?

IamCrazyD started a new conversation Maximum Function Nesting Level Of '100' Reached, Aborting Laravel 5.1 • 2 years ago

I am making an ecommerce web application in Laravel 5.1. While examining the application's admin panel for editing a particular product, I got an exception:

FatalErrorException in Container.php line 1057:
Maximum function nesting level of '100' reached, aborting!

I have implemented Repository Pattern in my application and it is still in development stage.

routes.php

Route::get('/admin/products', 'AdminProductsController@index');
Route::get('/admin/products/create', 'AdminProductsController@create');
Route::post('/admin/products', 'AdminProductsController@store');
Route::get('/admin/products/{id}/edit', 'AdminProductsController@edit');

AdminProductsController.php

<?php

namespace App\Http\Controllers;

use App\Category;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use App\Http\Requests\ProductRequest;
use App\Product;
use App\Repositories\Contracts\ProductRepositoryInterface;
use Illuminate\Http\Request;

class AdminProductsController extends Controller
{
    protected $prd;

    public function __construct(ProductRepositoryInterface $product)
    {
        $this->middleware('admin_logged_in');
        $this->prd = $product;
    }

    public function index()
    {
        $products = $this->prd->getAllProducts();

        return view('admin.products.index', compact('products'));
    }

    public function create()
    {
        $categoryList = Category::enabled()->lists('name', 'id');

        return view('admin.products.create', compact('categoryList'));
    }

    public function store(ProductRequest $request)
    {
        if($request->ajax()) {

            $this->prd->storeNewProduct($request);

            return response([
                'status' => 'success',
                'title' => 'Success !',
                'msg' => 'You have successfully created the product. Reloading in 5 seconds.'
            ]);
        }
    }

    public function edit($id)
    {
        $product = $this->prd->findProductById($id);

        $categoryList = Category::enabled()->lists('name', 'id');

        return view('admin.products.edit', compact('product', 'categoryList'));
    }
}

ProductRepositoryInterface.php

<?php

namespace App\Repositories\Contracts;

use App\Http\Requests\ProductRequest;

interface ProductRepositoryInterface {

    public function getAllProducts();

    public function storeNewProduct(ProductRequest $request);

    public function findProductById($id);
}

ProductRepository.php

<?php

namespace App\Repositories\Eloquent;

use App\Http\Requests\ProductRequest;
use App\Product;
use App\Repositories\Contracts\ProductRepositoryInterface;
use Illuminate\Http\Request;

class ProductRepository implements ProductRepositoryInterface
{
    /**
     * Display all the products in descending order.
     * 
     * @return array
     */
    public function getAllProducts()
    {
        return Product::latest()->get();
    }

    /**
     * Insert the new product model in the database.
     * 
     * @param  App\Http\Requests\ProductRequest $request
     * @return App\Product
     */
    public function storeNewProduct(ProductRequest $request)
    {
        $request['description']  = htmlspecialchars($request->input('description'));
        $request['special_note'] = htmlspecialchars($request->input('special_note'));

        $product = Product::create( $request->all() );

        $product->categories()->attach( $request->input('category_id') );

        return $product;
    }

    /**
     * Get the product model of the given id from the database.
     * 
     * @param  int $id
     * @return App\Product
     */
    public function findProductById($id)
    {
        return Product::find($id);
    }
}

The problem is when I try to edit the product from the admin panel, I get the above exception, though I can insert a new product from the admin panel.

I know that I can increase the xdebug.max_nesting_level = 100 to xdebug.max_nesting_level = 500, but this is not what I am looking for. I am developing the application for a client and they, probably, are having their own server. Thus, I cannot use this as my solution.

By doing some research, I was brought to this question: http://stackoverflow.com/questions/8656089/solution-for-fatal-error-maximum-function-nesting-level-of-100-reached-abor, but the accepted answer is using wamp as his server and I am using LAMP.

What / where is the mistake that I have made ?

Any help is highly appreciated. Thanks.

P.S.: I am using Ubuntu 14.04 LTS x64bit Architecture with LAMP installed. Also I am using Form Model Binding.

15th August, 2015

IamCrazyD left a reply on Got TokenMismatchException In VerifyCsrfMiddleware.php Line 16 Laravel 5 • 2 years ago

Yeah.. It was the configuration of the package that I didn't care to configure correctly. In that, they had asked to change the value of remove_csrf_check, and I had kept it as default only. Changing that to store/thank-you did the work.

I appreciate the help you did to me. I was not knowing that we can also remove specific routes from hitting the middleware. Thank you for that..

14th August, 2015

IamCrazyD left a reply on Got TokenMismatchException In VerifyCsrfMiddleware.php Line 16 Laravel 5 • 2 years ago

Well, @paradox, I am getting that exception on the thank you page.., So, the $except property should be I guess

/**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        '/store/thank-you', // retrieving the response from CCAvenue gateway
    ];

Right ?

IamCrazyD left a reply on Got TokenMismatchException In VerifyCsrfMiddleware.php Line 16 Laravel 5 • 2 years ago

@paradox The values are coming from the payment integrated website, i.e., from CCAvenue website. So, how can I add the token to that ?

IamCrazyD started a new conversation Got TokenMismatchException In VerifyCsrfMiddleware.php Line 16 Laravel 5 • 2 years ago

I am making an ecommerce web application using Laravel 5.

Now I am stuck at the payment integration. I am using CCAvenue as my payment integration, but there is no support provided from the ccavenue itself for laravel framework.

So, after a bit of research, I got this package called Indipay. This package works completely fine. However, I get TokenMismatchException. Though the transaction is successful and I do get the notification of the payment being received.

routes.php

Route::post('/store/proceed-to-checkout', 'CheckoutController@proceedToCheckout');
Route::get('/store/thank-you', 'PagesController@getThankYou');

CheckoutController.php

public function proceedToCheckout(Request $request)
{
    $orderCode = Order::latest()->limit(1)->first();
    $newOrderCode = ($orderCode) ? ++$orderCode->order_code : 'ORD-000000001';

    $parameters = [
        'merchant_id' => $request->get('merchant_id'),
        'currency' => $request->get('currency'),
        'redirect_url' => $request->get('redirect_url'),
        'cancel_url' => $request->get('cancel_url'),
        'language' => 'EN',
        'order_id' => $newOrderCode,
        'actionId' => $request->get('actionID'),
        'TxnType' => $request->get('TxnType'),
        'amount' => $request->get('amount'),
        'tid' => time().rand(111,999)
    ];

    return Indipay::purchase($parameters);
}

PagesController.php

public function getThankYou(Request $request)
{
    $ordCode = Session::get('ordCode');

    $response = Indipay::response($request);

    dd($response);

    //return view('version-seven.pages.thank_you', compact('ordCode'));
}

Kernel.php

<?php namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel {

    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
        'Illuminate\Cookie\Middleware\EncryptCookies',
        'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
        'Illuminate\Session\Middleware\StartSession',
        'Illuminate\View\Middleware\ShareErrorsFromSession',
        //'App\Http\Middleware\VerifyCsrfToken',
        'App\Http\Middleware\VerifyCsrfMiddleware',
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => 'App\Http\Middleware\Authenticate',
        'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
        'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
        'admin' => 'App\Http\Middleware\AdminAuthentication',
    ];

}

12th June, 2015

IamCrazyD started a new conversation GroupBy Returns Only 1 Result Set Of That Particular Id In QueryBuilder Laravel 5 • 2 years ago

I have 2 Models: Product and Carousel. Both of them have Many To Many relationship established.

I have a pivot table carousel_product.

In the pivot table, I have few datas like so:

id    carousel_id    product_id    created_at    updated_at
 1            2                       2                   --                     --
 2           2                       3                   --                     --
 3           2                       4                   --                     --
 4           3                       5                   --                     --
 5           3                       6                   --                     --
 6           3                       7                   --                     --

Now I want to retrieve all the products that are in carousel_id = 2 and carousel_id = 3

For this, I am using Query Builder in my controller:

public function index()
{
    $carousels = Carousel::where('display', 'Enabled')->get();
    $products = DB::table('carousel_product AS cp')
                ->join('products AS p', 'p.id', '=', 'cp.product_id')
                ->join('carousels AS c', 'c.id', '=', 'cp.carousel_id')
                ->select(
                    'p.id AS prod_id',
                    'p.name AS prod_name',
                    'p.code AS prod_code',
                    'p.short_description AS prod_short_desc',
                    'p.price AS prod_price',
                    'p.discount_price AS prod_disc_price'
                )->groupBy('cp.carousel_id')->get();
    dd( $products );
    return view( 'home', compact( 'carousels', 'products' ) );
}

The output of dd( $products ) is product_id of 2 and 7

I want all the products of that particular carousel_id and display it in my view for that carousel only.

P.S.: All the values are coming from the database.

How can I achieve this ?

8th June, 2015

IamCrazyD started a new conversation Delete A Record From Table Using Ajax In Laravel 5 • 2 years ago

I want to delete the record using ajax.

Here's the view:

@foreach( $products as $product )
    <tr>
        <td>{{ $product->code }}</td>
        <td>{{ $product->name }}</td>
        <td>{{ $product->display }}</td>
        <?php $time = date('d M, Y h:i:s A', strtotime($product->created_at)); ?>
        <td>{{ $time }}</td>
        <td>
            <a href="{{ url('/admin/products/' . $product->id . '/edit') }}" class="links-dark edits pull-left">
                <i class="fa fa-edit fa-lg"></i>
            </a>
            <div id="deleteTheProduct">
                {!! Form::open(['method' => 'DELETE', 'id' => 'formDeleteProduct', 'action' => ['AdminProductsController@destroy', $product->id]]) !!}
                    {!! Form::button( '<i class="fa fa-trash fa-lg"></i>', ['type' => 'submit', 'class' => 'delete text-danger deleteProduct','id' => 'btnDeleteProduct', 'data-id' => $product->id ] ) !!}
               {!! Form::close() !!}
           </div>
       </td>
   </tr>
@endforeach

Here's the controller:

public function destroy( $id, Request $request ) {
    $product = Product::findOrFail( $id );

    if ( $request->ajax() ) {
        $product->delete( $request->all() );

        return response(['msg' => 'Product deleted', 'status' => 'success']);
    }
    return response(['msg' => 'Failed deleting the product', 'status' => 'failed']);
}

Here's the Ajax:

$('.deleteProduct').on('click', function(e) {
    var inputData = $('#formDeleteProduct').serialize();

    var dataId = $('#btnDeleteProduct').attr('data-id');

    $.ajax({
        url: '{{ url('/admin/products') }}' + '/' + dataId,
        type: 'POST',
        data: inputData,
        success: function( msg ) {
            if ( msg.status === 'success' ) {
                toastr.success( msg.msg );
                setInterval(function() {
                    window.location.reload();
                }, 5900);
            }
        },
        error: function( data ) {
            if ( data.status === 422 ) {
                toastr.error('Cannot delete the category');
            }
        }
    });

    return false;
});

The thing is that, this deletes the product, but only the first row and not the one that is clicked.

I want to delete the product which is clicked.

How do I achieve this ? Kindly help me.

23rd April, 2015

IamCrazyD started a new conversation Laravel 5 Password Reset Not Working • 2 years ago

I am working on laravel 5 eCommerce web portal.

I am having an issue when the user updates the password using the ready made scripts.

The issue is that I can send the link to the customer perfectly without any issue and the customer can change his password also. But when logged out and re-logging in, I get the error as Invalid credentials.

In my routes.php, I have this:

Route::controllers([
    'auth' => 'Auth\AuthController',
    'password' => 'Auth\PasswordController',
]);

This is the login page:

<form class="form-horizontal" role="form" method="POST" action="{{ url('/login') }}">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">

    <div class="form-group">
        <label class="col-md-4 control-label">E-Mail Address</label>
        <div class="col-md-6">
            <input type="email" class="form-control" name="email" value="{{ old('email') }}">
        </div>
    </div>

    <div class="form-group">
        <label class="col-md-4 control-label">Password</label>
        <div class="col-md-6">
            <input type="password" class="form-control" name="password">
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-4"></div>
        <div class="col-md-4">
            <a href="{{url('/password/email')}}">Forgot Password</a>
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-6 col-md-offset-4">
            <button type="submit" class="btn btn-primary btn-block">Login</button>
        </div>
    </div>
</form>

When the login button is clicked on the login form page, the postLogin method is called. Here's the code

public function postLogin( Request $request ) {
    $this->validate( $request, [
        'email'     => ['required', 'exists:users,email,role,customer'],
        'password'  => 'required'
    ]);

    $credentials = $request->only('email', 'password');

    if ( \Auth::attempt($credentials) ) {
        \Session::flash('logged_in', 'You have successfully logged in.');
        return redirect('/');
    }

    return redirect('/login')->withInput($request->all())->withErrors(['email' => 'Invalid Email Address Or Password']);
}

I just realize that login is not checking for the hash and hence returning false, on doing dd(\Hash::check($request->password, $user->password)), after updating the password and re-logging in. What could be the issue with this ?

Where have I made mistake ? Kindly guide me.

Thanks in advance.

P.S.: I am using the defaults only to update the password, rest all, I have made the controllers and models which are all working fine without any issue.

21st April, 2015

IamCrazyD started a new conversation Laravel 5 - Blurry Image After Upload - Intervention • 2 years ago

I am making an eCommerce web portal. I am trying to upload the image in different resolutions, which is working completely fine.

But the problem is that, if I view it in the browser after uploading, I get to see the blurry image which is not what I want. I want that after the upload, the image should be clearly seen and it should not be blurry.

Here's the controller method for it:

public function store( AddProductRequest $request ) {
    if(\Auth::guest()) {
        return redirect('/admin');
    }

    $imageType = [
        'thumbnail' => [
            'height' => 75,
            'width' => 75
        ],
        'product' => [
            'height' => 450,
            'width' => 450
        ],
        'cart' => [
            'height' => 200,
            'width' => 200
        ]
    ];

    if ( $request->file( 'image_file' ) ) {
        $fileName = $request->file( 'image_file' )->getClientOriginalName();

        $fileName = explode( '.', $fileName );
        $image = \Image::make( $request->file( 'image_file' ) );
        $path = public_path( 'images/uploads/' );

        foreach ($imageType as $key => $value) {
            if ($key == 'thumbnail') {
                $image->resize( $value['width'], $value['height'], function( $constraint ) {
                    $constraint->aspectRatio();
                });
                $image->save( $path.$fileName[0]."-thumbnail-". $value['width'] ."-".$value['height'] .".jpg", 100 );
            } elseif ( $key == 'product' ) {
                $image->resize( $value['width'], $value['height'], function( $constraint ) {
                    $constraint->aspectRatio();
                });
                $image->save( $path.$fileName[0]."-product-". $value['width'] ."-".$value['height'] .".jpg", 100 );
            } elseif ( $key == 'cart' ) {
                $image->resize( $value['width'], $value['height'], function( $constraint ) {
                    $constraint->aspectRatio();
                });
                $image->save( $path.$fileName[0]."-cart-". $value['width'] ."-".$value['height'] .".jpg", 100 );
            }
        }
    }       

    $product = Product::create( $request->all() );

    $product->tags()->attach( $request->input('tags') );

    \Session::flash('product_added', 'Product has been successfully added in the database.');
    return redirect('admin/products');
}

How do I avoid displaying blurry image after upload ?

Kindly help me. Thanks in advance.

9th April, 2015

IamCrazyD left a reply on Update The Value If Same Key Of Array Or Insert As New Value • 2 years ago

@foxted I know I can have a package like you just mentioned, but I want to learn and then move to pre-built packages.

IamCrazyD started a new conversation Update The Value If Same Key Of Array Or Insert As New Value • 2 years ago

I am making an eCommerce web application and I am a newbie.

What I am trying to achieve is when a product exists in the session, I want to update the quantity of that product when Add to Cart button is clicked. And if it doesn't exists in the session, I want to insert it in the session.

Code that I have tried so far

public function store( $id ) {

        $product = Product::findOrFail( $id );

    if ( \Session::has( 'cart' ) && is_array( \Session::get('cart') ) ) {
        \Session::push('cart', ['product' => (int)$id, 'quantity' => 1 ]);
    } else {
        \Session::put('cart', ['product' => (int)$id, 'quantity' => 1 ]);
    }

    \Session::flash('added_product', 'Product Added in the cart');

    return \Redirect::back();
}

The output that I get for the above code is:

array:3 [▼
  0 => array:2 [▼
    "product" => 1
    "quantity" => 1
  ]
  1 => array:2 [▼
    "product" => 2
    "quantity" => 1
  ]
  2 => array:2 [▼
    "product" => 1
    "quantity" => 1
  ]
]

The "product" is the id of the product.

For 1 product, it is working fine, but when I try to add the same product, it gets appended.

How do I resolve this ? Kindly help me out.

7th April, 2015

IamCrazyD left a reply on Laravel 5: Multiple User Authentication System • 2 years ago

@frezno I agree to what you are trying to say. But I am at the learning stage of Laravel.

@MattCroft Here's the routes.php code:

Route::get('admin', 'AdministratorController@index');

Route::post('admin/login', 'AdministratorController@postLogin');

When trying to login, I get the following error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'LaraJect.users' doesn't exist (SQL: select * from `users` where `email` = myemail@gmail.com limit 1)

IamCrazyD left a reply on Laravel 5: Multiple User Authentication System • 2 years ago

Okay.. Here's what I have tried so far..

My AdministratorController:

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Auth;

use Illuminate\Http\Request;


class AdministratorController extends Controller {

    public function index() {
        return view('admin.admin_login');
    }

    public function postLogin(Request $request) {
        $this->validate($request, 
            ['email' => 'required', 'password' => 'required'
        ]);
        $credentials = $request->only('email', 'password');

        if (\Auth::attempt($credentials)) {
            $name = \Auth::user()->name;
            return 'Welcome Admin';
        }
    }

}

My Administrator Model:

<?php namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;

class Administrator extends Model implements AuthenticatableContract {

    use Authenticatable;

    protected $table = 'administrators';

    protected $fillable = [
        'name', 'email', 'password'
    ];

}

IamCrazyD left a reply on Laravel 5: Multiple User Authentication System • 2 years ago

Will that work ? Asking because I am new to Laravel framework.

IamCrazyD left a reply on Laravel 5: Multiple User Authentication System • 2 years ago

My table name is administrators and my Model name is Administrators

IamCrazyD started a new conversation Laravel 5: Multiple User Authentication System • 2 years ago

I am trying to make an eCommerce web application using Laravel 5. But it seems that I am stuck at the very first stage of it - Authentication. Well, In my application, there are 2 entities (Administrator and the Normal User).

I have created the administrator table having columns id, name, email and password using the migration.

After some research, I came to know that in the Administrator Model, I have to declare the following code :=>

protected $table = 'administrators';

So I tried that, but that didn't helped me out.

What could be the issue ?

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.