ehsanquddusi

ehsanquddusi

Member Since 3 Years Ago

Srinagar

Experience Points 6,585
Experience Level 2

3,415 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 25
Lessons
Completed
Best Reply Awards 5
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

28 Sep
8 months ago

ehsanquddusi left a reply on Url Rewriting Not Working Outside Laravel For Mix

I am trying to make url rewrite work. Addimg it as false will stop the rewrites?

ehsanquddusi started a new conversation Url Rewriting Not Working Outside Laravel For Mix

I am using following config in my webpack.mix.js file

mix.options({
    publicPath: 'assets'
});
mix.styles([
        'assets/v3/plugins/pace/pace-theme-flash.css',
        'assets/v3/plugins/boostrapv3/css/bootstrap.min.css',
        'assets/v3/plugins/font-awesome/css/font-awesome.css',
        'assets/v3/plugins/jquery-scrollbar/jquery.scrollbar.css',
        'assets/v3/framework/css/pages-icons.min.css',
        'assets/v3/framework/css/pages.min.css',
        'assets/v3/framework/css/themes/corporate.min.css',
        'assets/v3/css/style.css'
    ], 'assets/compiled/css/core.css');

But the image/font urls in the files are not rewritten in the final combined file. I am using this outside laravel.

I am using laravel-mix version 2.1.14.

21 Apr
1 year ago

ehsanquddusi left a reply on Error In Eloquent Pagination Outside Laravel

@jlrdw - I have updated my question with composer.json eloquent dependency. Please have a look.

ehsanquddusi started a new conversation Error In Eloquent Pagination Outside Laravel

I am using Illuminate/database package outside Laravel with my CodeIgniter setup. The initialization is done using Capsule class like this

use Illuminate\Database\Capsule\Manager as CapsuleManager; use Illuminate\Events\Dispatcher; use Illuminate\Container\Container;

class Capsule extends CapsuleManager { public function __construct() { parent::__construct();

require_once __DIR__.'/../config/database.php';
$db = (object) $db['default'];

$this->addConnection(array(
    'driver'    => 'mysql',
    'host'      => $db->hostname,
    'database'  => $db->database,
    'username'  => $db->username,
    'password'  => $db->password,
    'charset'   => $db->char_set,
    'collation' => $db->dbcollat,
    'prefix'    => $db->dbprefix,
));

$this->setEventDispatcher(new Dispatcher(new Container));

// Make this Capsule instance available globally via static methods... (optional)
$this->setAsGlobal();

// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
$this->bootEloquent();

} } I had it running on illuminate/database 5.2. Recently I updated it to illuminate/database 5.5. My Eloquent paginate() has stopped working. The links() method on eloquent collection gives following error.

Call to a member function make() on null With a stack trace to

return new HtmlString(static::viewFactory()->make($view ?: static::$defaultView, array_merge($data, [ in vendor\illuminate\pagination\LengthAwarePaginator.php on Line 90

27 Jan
1 year ago

ehsanquddusi left a reply on Displaying User Name Of A Relationship

Is User class defined ? What error are you getting?

ehsanquddusi left a reply on Unable To Access Methods On User Model Using Auth::user()

Try composer dumpautoload. It should work.

ehsanquddusi left a reply on Count All Payments Inside Table

But $payments->get() is not the optimal way for aggregate functions. This will result in unnecessary load on your server. $payments->get() first returns the Collection and then you are running sum on collection, which is not advisable.

ehsanquddusi left a reply on Count All Payments Inside Table

You can use sum aggregate function, like

$total = Payment::sum('nominal');

Assuming, you have a model Payment for your payments table.

12 Jan
1 year ago

ehsanquddusi left a reply on Upload Large Csv File To Mysql With Laravel

Spout (https://github.com/box/spout) is the best library to read and write spreadsheet files (CSV, XLSX and ODS), in a fast and scalable way. Its streaming mechanism makes it incredibly fast with memory fingerprint of around 3MB, irrespective of file size. It is capable of processing filesizes in GBs.

Install using composer require box/spout and then simply use

use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Common\Type;

$reader = ReaderFactory::create(Type::XLSX); // for XLSX files
//$reader = ReaderFactory::create(Type::CSV); // for CSV files
//$reader = ReaderFactory::create(Type::ODS); // for ODS files

$reader->open($filePath);

foreach ($reader->getSheetIterator() as $sheet) {
    foreach ($sheet->getRowIterator() as $row) {
        // do stuff with the row
    }
}

$reader->close();

ehsanquddusi started a new conversation Help With Maatwebsite/Laravel-Excel

I am using Maatwebsite/Laravel-Excel to import excel file into my application. I want to use ExcelFile injections so that I can use it like this in my controller

class ExampleController extends Controller {

    public function importUserList(UserListImport $import)
    {
        // get the results
        $results = $import->get();
    }

}

In the Maatwebsite/Laravel-Excel example, it says to make a class like this to return and load excel file

class UserListImport extends \Maatwebsite\Excel\Files\ExcelFile {

    public function getFile()
    {
        return storage_path('exports') . '/file.csv';
    }

    public function getFilters()
    {
        return [
            'chunk'
        ];
    }

}

This method is used to return filename to be imported.

public function getFile()
    {
        return storage_path('exports') . '/file.csv';
    }

My issue is that filename is stored in database and is dynamic. How can I use the Import class with my dynamic filenames.

Docs for Maatwebsite/Laravel-Excel is available at http://www.maatwebsite.nl/laravel-excel/docs/import

13 Dec
1 year ago

ehsanquddusi left a reply on How To Enhance This Library.

@Lars-Janssen An example on this codebase of the best practice that you mentioned would be appreciated.

ehsanquddusi started a new conversation How To Enhance This Library.

This library is part of accounting system. Two major models are involved. For every transaction there is an entry in AccountTransaction model and corresponding 2 entries in AccountJournal model. For non-cash entries, reference details go to AccountTransactionDetail model. How the code can be rewritten more efficiently, as I see lot of repetition in it.

<?php

namespace App\Libraries;

use App\AccountPeriod;
use App\AccountTransaction;
use App\AccountGroup;
use App\AccountLedger;
use App\AccountJournal;
use DB;
use Auth;

class Accounts
{
    protected $entity = [];
    protected $period;
    protected $ledgerWise = false;
    protected $discounts;
    protected $balances;
    protected $ledgers = [];
    protected $reference;
    protected $amount;
    protected $paymentMode;

    /**
     * Entity involved in the transaction
     *
     * @param $entity_type
     * @param $entity_id
     * @return \App\Libraries\Accounts
     */
    public function entity($entity_type, $entity_id)
    {
        $this->entity = [
            'type' => $entity_type,
            'id' => $entity_id,
        ];
        return $this;
    }

    /**
     * Accounting period
     *
     * @param \App\AccountPeriod $period
     * @return \App\Libraries\Accounts
     */
    public function period($period)
    {
        $this->period = $period;
        return $this;
    }

    /**
     * Ledgerwise results
     *
     * @return \App\AccountPeriod
     */
    public function ledgerWise()
    {
        $this->ledgerWise = true;
        return $this;
    }

    /**
     * Calculates account balance of an entity
     *
     * Returns ledger wise balances or aggregate balance
     *
     * @return mixed
     */
    public function balances()
    {
        $balances = AccountJournal::having('total', '>', 0)
            ->whereHas('ledger', function ($q) {
                return $q->where('name', 'Accounts Receivable');
            });
        if (isset($this->period)) {
            $balances->ofPeriod($this->period);
        }
        if (!empty($this->entity)) {
            $balances->ofEntity($this->entity['type'], $this->entity['id']);
        } else {
            $balances->groupBy(['entity_type', 'entity_id']);
        }
        if ($this->ledgerWise) {
            $balances->select(['linked_ledger_id AS ledgerId', 'account_ledgers.name AS ledgerName'])
                ->join('account_ledgers', 'account_journals.linked_ledger_id', '=', 'account_ledgers.id')
                ->groupBy(['ledgerId']);
        }
        return $balances->addSelect(['entity_type', 'entity_id', DB::raw('SUM(amount) AS total')])
            ->get();
    }

    /**
     * Discounts given to account
     *
     * @param array $discounts Associative array of ledger wise discounts
     * @return \App\AccountPeriod
     */
    public function discounts($discounts)
    {
        $this->discounts = $discounts;
        return $this;
    }

    /**
     * Processes payment against an account
     *
     * Calculates balances, adjusts discounts given (if any)
     * and posts to relevant ledgers
     *
     * @return bool|void
     */
    public function pay()
    {
        if (empty($this->getEntityType())) {
            return false;
        }
        $this->processDiscounts();
        switch ($this->getMode()) {
            case 'Cash':
                $debitLedger = $this->getCashLedger();
                $tranType = 'Payment';
                break;
            case 'Bank':
                $debitLedger = $this->getBankLedger();
                $tranType = 'Payment';
                break;
            case 'Adjustment':
                $debitLedger = $this->getDiscountsLedger();
                $tranType = 'Journal';
                break;
            default:
                return false;
        }
        if ($this->getAmount() <= 0) {
            return;
        }
        DB::transaction(function() use(&$t, $debitLedger, $tranType) {
            $t = AccountTransaction::create([
                'period_id' => $this->getPeriod(),
                'entity_type' => $this->getEntityType(),
                'entity_id' => $this->getEntityId(),
                'type' => $tranType,
                'amount' => $this->getAmount(),
            ]);
            if ($debitLedger->name != 'Cash') {
                $t->detail()->create([
                    'ref_id' => $this->getReferenceId(),
                    'ref_date' => $this->getReferenceDate(),
                    'ref_desc' => $this->getReferenceDesc(),
                ]);
            }

            foreach ($this->getBalances() as $balance)
            {
                if ($this->getAmount() >= $balance->total) {
                    $amount = $balance->total;
                    $this->amount($this->getAmount() - $amount);
                } else {
                    $amount = $this->getAmount();
                    $this->amount(0);
                }
                AccountJournal::create([
                    'period_id' => $this->getPeriod(),
                    'entity_type' => $this->getEntityType(),
                    'entity_id' => $this->getEntityId(),
                    'ledger_id' => $this->getReceivableLedger()->id,
                    'linked_ledger_id' => $balance->ledgerId,
                    'transaction_id' => $t->id,
                    'amount' => -($amount),
                    'created_by' => Auth::id(),
                ]);

                AccountJournal::create([
                    'period_id' => $this->getPeriod(),
                    'entity_type' => $this->getEntityType(),
                    'entity_id' => $this->getEntityId(),
                    'ledger_id' => $debitLedger->id,
                    'linked_ledger_id' => $balance->ledgerId,
                    'transaction_id' => $t->id,
                    'amount' => $amount,
                    'created_by' => Auth::id(),
                ]);
                if ($this->getAmount() == 0) {
                    break;
                }
            }
            // If there is no balance, consider advance
            if ($this->getAmount() > 0) {
                AccountJournal::create([
                    'period_id' => $this->getPeriod(),
                    'entity_type' => $this->getEntityType(),
                    'entity_id' => $this->getEntityId(),
                    'ledger_id' => $this->getAdvancesLedger()->id,
                    'transaction_id' => $t->id,
                    'amount' => -($this->getAmount()),
                    'created_by' => Auth::id(),
                ]);

                AccountJournal::create([
                    'period_id' => $this->getPeriod(),
                    'entity_type' => $this->getEntityType(),
                    'entity_id' => $this->getEntityId(),
                    'ledger_id' => $debitLedger->id,
                    'transaction_id' => $t->id,
                    'amount' => $this->getAmount(),
                    'created_by' => Auth::id(),
                ]);
            }
            return $t;
        });
        return $t;
    }

    /**
     * Payment mode for the transaction
     *
     * @param $mode Payment mode
     * @return \App\Libraries\Accounts
     */
    public function mode($mode)
    {
        $this->paymentMode = $mode;
        return $this;
    }

    /**
     * Amount for the transaction
     *
     * @param $amount Amount
     * @return \App\Libraries\Accounts
     */
    public function amount($amount)
    {
        $this->amount = $amount;
        return $this;
    }

    /**
     * Reference details for the transaction
     *
     * @param $ref_id
     * @param null $ref_date
     * @param null $ref_desc
     * @return \App\Libraries\Accounts
     */
    public function reference($ref_id, $ref_date = null, $ref_desc = null)
    {
        if (is_array($ref_id)) {
            $this->reference = $ref_id;
        } else {
            $this->reference = [
                'id' => $ref_id,
                'date' => $ref_date,
                'desc' => $ref_desc,
            ];
        }
        return $this;
    }

    /**
     * Adjusts discounts against balances, ledger wise
     *
     * @return bool
     */
    public function processDiscounts()
    {
        if (!$this->getDiscounts()) {
            return false;
        }

        foreach ($this->getBalances() as $balance)
        {
            if (in_array($balance->ledgerId, array_keys($this->getDiscounts())) &&
                $this->getDiscounts()[$balance->ledgerId] > 0) {
                DB::transaction(function () use($balance) {
                    $t = AccountTransaction::create([
                        'period_id' => $this->getPeriod(),
                        'entity_type' => $this->getEntityType(),
                        'entity_id' => $this->getEntityId(),
                        'type' => 'Journal',
                        'amount' => $this->getDiscounts()[$balance->ledgerId],
                    ]);

                    $t->detail()->create([
                        'ref_id' => $this->getReferenceId(),
                        'ref_date' => $this->getReferenceDate(),
                        'ref_desc' => $this->getReferenceDesc(),
                    ]);


                    AccountJournal::create([
                        'period_id' => $this->getPeriod(),
                        'entity_type' => $this->getEntityType(),
                        'entity_id' => $this->getEntityId(),
                        'ledger_id' => $this->getReceivableLedger()->id,
                        'linked_ledger_id' => $balance->ledgerId,
                        'transaction_id' => $t->id,
                        'amount' => -($this->getDiscounts()[$balance->ledgerId]),
                        'created_by' => Auth::id(),
                    ]);

                    AccountJournal::create([
                        'period_id' => $this->getPeriod(),
                        'entity_type' => $this->getEntityType(),
                        'entity_id' => $this->getEntityId(),
                        'ledger_id' => $this->getDiscountsLedger()->id,
                        'linked_ledger_id' => $balance->ledgerId,
                        'transaction_id' => $t->id,
                        'amount' => $this->getDiscounts()[$balance->ledgerId],
                        'created_by' => Auth::id(),
                    ]);
                });
            }
        }
        unset($this->balances);
    }

    /**
     * Account balances
     *
     * @return mixed
     */
    public function getBalances()
    {
        if (!isset($this->balances)) {
            $this->balances = $this->ledgerWise()->balances();
        }
        return $this->balances;
    }

    /**
     * Receivable ledger
     *
     * @return \App\AccountLedger
     */
    public function getReceivableLedger()
    {
        if (!isset($this->ledgers['receivable'])) {
            $this->ledgers['receivable'] = AccountLedger::whereName('Accounts Receivable')
                ->first();
        }
        return $this->ledgers['receivable'];
    }

    /**
     * Discounts ledger
     *
     * @return \App\AccountLedger
     */
    public function getDiscountsLedger()
    {
        if (!isset($this->ledgers['discounts'])) {
            $this->ledgers['discounts'] = AccountLedger::whereName('Discounts')
                ->first();
        }
        return $this->ledgers['discounts'];
    }

    /**
     * Advances ledger
     *
     * @return \App\AccountLedger
     */
    public function getAdvancesLedger()
    {
        if (!isset($this->ledgers['advances'])) {
            $this->ledgers['advances'] = AccountLedger::whereName('Advances')
                ->first();
        }
        return $this->ledgers['advances'];
    }

    /**
     * Cash ledger
     *
     * @return \App\AccountLedger
     */
    public function getCashLedger()
    {
        if (!isset($this->ledgers['cash'])) {
            $this->ledgers['cash'] = AccountLedger::whereName('Cash')
                ->first();
        }
        return $this->ledgers['cash'];
    }

    /**
     * Bank ledger
     *
     * @return \App\AccountLedger
     */
    public function getBankLedger()
    {
        if (!isset($this->ledgers['bank'])) {
            $this->ledgers['bank'] = AccountLedger::whereName('Bank')
                ->first();
        }
        return $this->ledgers['bank'];
    }

    /**
     * Accounting period
     *
     * @return $id Accounting period id
     */
    public function getPeriod()
    {
        if (!isset($this->period)) {
            $this->period = AccountPeriod::active()->first()->id;
        }
        return $this->period;
    }

    /**
     * Entity type of transaction
     *
     * @return mixed
     */
    public function getEntityType()
    {
        return $this->entity['type'];
    }

    /**
     * Entity id of transaction
     * 
     * @return mixed
     */
    public function getEntityId()
    {
        return $this->entity['id'];
    }

    public function getDiscounts()
    {
        return isset($this->discounts) ? $this->discounts : false;
    }

    public function getReferenceId()
    {
        if(isset($this->reference)) {
            return $this->reference['id'];
        }
        return null;
    }

    public function getReferenceDate()
    {
        if(isset($this->reference)) {
            return $this->reference['date'];
        }
        return null;
    }

    public function getReferenceDesc()
    {
        if(isset($this->reference)) {
            return $this->reference['desc'];
        }
        return null;
    }

    public function getMode()
    {
        return $this->paymentMode;
    }

    public function getAmount()
    {
        return $this->amount;
    }
}

06 Dec
1 year ago

ehsanquddusi left a reply on Laravel Eloquent Query Has Issues, While As Raw Query Works Fine

Found the solution. Laravel 5.5 by default works in MySQL strict mode which is generating the error. Making strict to false in database config fixes the issue.

05 Dec
1 year ago

ehsanquddusi started a new conversation Laravel Eloquent Query Has Issues, While As Raw Query Works Fine

I am writing a query in Laravel 5.5 Eloquent with for which toSql() returns

SELECT 
    `entity_type`, `entity_id`, SUM(amount) AS total
FROM
    `account_journals`
WHERE
    EXISTS( SELECT 
            *
        FROM
            `account_ledgers`
        WHERE
            `account_journals`.`ledger_id` = `account_ledgers`.`id`
                AND `name` = ?
                AND `account_ledgers`.`deleted_at` IS NULL)
GROUP BY `entity_type` , `entity_id`
HAVING `total` > ?

It shows error and doesn't run

SQLSTATE[42000]: Syntax error or access violation: 1463 Non-grouping field 
'total' is used in HAVING clause (SQL: select `entity_type`, `entity_id`, 
SUM(amount) AS total from `account_journals` where exists (select * from 
`account_ledgers` where `account_journals`.`ledger_id` = 
`account_ledgers`.`id` and `name` = Accounts Receivable and 
`account_ledgers`.`deleted_at` is null) group by `entity_type`, `entity_id` 
having `total` > 0)

If I run the same query directly, it is working fine. What can be the problem.

23 Oct
1 year ago

ehsanquddusi left a reply on Issue With Laravel File Uploads On Local Storage

Not related to the question.

ehsanquddusi started a new conversation Issue With Laravel File Uploads On Local Storage

I am using $request->file('photo')->store('public/photos'); to store files in public/photos directory under storage. Created a link to storage from public directory using artisan storage:link. The output of $request->file('photo')->store('public/photos'); is stored in db against the photo field. While retrieving the photo in view, I use asset() helper which output the link as domain.com/storage/public/photos/photo.jpg which returns 404 error. It should actually return domain.com/storage/photos/photo.jpg as public/storage is linked to app/storage/public. Please help.

04 Jan
2 years ago

ehsanquddusi left a reply on Check If Model Exists For Use In Custom Method

@bobbybouwmann - It doesn't work.

My method is

public function reach()
{
    if ($this->exists()) {
        return 'exits';
    } else {
        return 'not exists';
    }
}

and I tried

$campaign = new Campaign;
print $campaign->reach();

and it gives me output as exists, while as this is a newly created instance of Campaign model and should show as not exists

ehsanquddusi started a new conversation Check If Model Exists For Use In Custom Method

I have created a method reach() inside Campaign model. The reach() method processes data from the model instance. How can I check whether the data is loaded in current instance or not? e.g,

$campaign = new Campaign;
$campaign->reach();

It won't work with this instance, since the eloquent object will be empty this time, but it should work with

$campaign = Campaign::find(1);
$campaign->reach();

Here $campaign will be instance with data loaded from campaigns table.

My question is, how can I know, if the object instance is newly created or loaded with data.

01 Jun
3 years ago

ehsanquddusi left a reply on Checking Existence And Syncing Data With Millions Of Rows

I tried Redis, but the footprint was too big. Finally managed using MySql, as the lookup size was within acceptable range.

21 Feb
3 years ago

ehsanquddusi started a new conversation Multiple Domain Routing

I have setup multi-domain routing in my laravel 5.2 app. What I want to achieve is if a user hits, membership.app, he should be served different homepage as compared to user who hits, erp.app domain.

Route::pattern('erp', 'erp.app|erp.domain.com');
Route::pattern('membership', 'membership.app|membership.domain.com');

Route::group(['middleware' => ['web', 'auth'], 'domain' => '{erp}'], function() {
    Route::get('/', 'HomeController@getIndex');
    Route::controller('members', 'MembersController');
    Route::controller('users', 'UsersController');
    Route::controller('settings', 'SettingsController');
});

Route::group(['middleware' => 'web', 'domain' => '{erp}'], function () {
    Route::controller('auth', 'Auth\AuthController');
});

Route::group(['middleware' => 'web', 'domain' => '{membership}'], function () {
    Route::controller('/', 'BecomeMemberController');
});

Route::group(['middleware' => 'web'], function () {
    Route::controller('ajax', 'AjaxController');
});

I tried this setup, but it breaks the code with first param in each controller method being the url instead of intended value.

Suppose I have a method hello in members controller.

public function hello($param1, $param2)
{
    ....
}

If I access erp.app/members/hello/1/2 url and try to print out $param1 of controller method, it returns erp.app instead of intended 1 in this case.

Please help.

17 Jan
3 years ago

ehsanquddusi left a reply on Missing Migration!

Can you share dump of your migration table?

ehsanquddusi left a reply on ManyToMany StoreController

For ManyToMany relation, you need one more table called pivot table to store the relations. In your case it will be

Subjects table

Schema::create('subjects', function (Blueprint $table) {
        $table->increments('id');
        $table->string('subject_name');
        $table->timestamps();
});

Levels table

Schema::create('levels', function (Blueprint $table) {
        $table->increments('id');
        $table->string('level_name');
        $table->timestamps();
});

Subject Levels table

Schema::create('level_subject', function (Blueprint $table) {
        $table->increments('level_id');
        $table->string('subject_id');
});

Subjects Model

public function levels() { return $this->belongsToMany('App\Subject'); } Levels Model

public function subjects() { return $this->belongsToMany('App\Subject'); }

Levels Controller

public function store(Requests\LevelsRequest $request)
{
    // This will save level
    $level = Levels::create($request->all());

    // You can save related subject this this.
    $level->subjects()->attach($subject_id);
    
    // Multiple subjects
    $level->subjects()->attach([1,2,3]);
    
return redirect('levels');
}

ehsanquddusi left a reply on File Upload Not Working

Your form should have enctype attribute set to support file uploads.

<form action="/upload" method="post" enctype="multipart/form-data">

ehsanquddusi started a new conversation Add Custom Attribute From Raw Query

I have a function named siblings which fetches all siblings of a user.

select siblings(id) as `siblings` from users where id = 1
12 Jan
3 years ago

ehsanquddusi left a reply on Building An SAsS App

Yes, this is the right way to do, as it will need minimum configuration on your side. CNAME is always better.

You can obviously filter which domains are allowed to point to your app.

You can also map the domain with user for some customization.

ehsanquddusi left a reply on Get Users Latest Messages Using Eloquent :)

Let us assume, you have an eloquent model named Message for the table.

You can have a simple query for Inbox and Sent messages of current user

// Inbox
$inbox = Message::where('to_id', Auth::user()->id)->get();
// Sent messages
$sent = Message::where('from_id', Auth::user()->id)->get();
$all = Message::where('to_id', Auth::user()->id)
    ->orWhere('from_id', Auth::user()->id)
    ->get();

Hope this helps.

ehsanquddusi left a reply on Custom Migration Command

First of all, why do you need to create a command for migration. By default when you run migration on production server, it asks for confirmation.

Meanwhile you can ask for confirmation by modifying your code.

if ($this->confirm('Do you wish to continue? [yes|no]')) { // }

public function fire()
{
    if ($this->confirm('Do you wish to continue? [yes|no]')) {
        $tenant = Tenant::find(1); 
        $this->tenantMigration($tenant);
    }
}
11 Jan
3 years ago

ehsanquddusi left a reply on Sorting Collection By Key Value, Tried KeyBy - Did Not Work

This can help

$types = [];
$collection->each(function($item, $key) {
    $types[$item->type][] = $item;
});
// Convert to collection
$types = collect($types);

ehsanquddusi left a reply on Authenticating With Join

You can simply use

if (Auth::attempt(['client_username' => ..., 'username' => ..., 'password' => ...])) {
    // User authenticated
}

ehsanquddusi left a reply on How To Update Migration In Laravel5.1

You may try

class ModifyUsersTable extends Migration
{
    public function up() 
    {
        Schema::table('users', function (Blueprint $table) { 
            $table->dropUnique('users_email_unique');
            $table->string('email')->unique()->nullable()->change(); 
        }); 
    }
}
03 Jan
3 years ago

ehsanquddusi started a new conversation Checking Existence And Syncing Data With Millions Of Rows

I am developing sms based service platform. In India, we have two different types of routes to send sms - promo & trans. Sms sent via promo route has to be checked against nationally maintained database (DND), which currently holds 231450000 mobile numbers.

My question is

  1. What is the efficient way to store this data (DND).
  2. What is the efficient way to check, whether the number exists within these numbers or not.
  3. Twice in a week, a delta dump of these numbers (DND) is provided by telecom authority. How to sync the dump with existing db.
  4. Should I use mysql to store this data, which will consist of mobile numbers, or any other in-memory storage?

EDIT:

  1. Each row of data consists of mobile number alongwith few preferences like area code, user preference etc
  2. The data dump provided twice a week contains only additions / deletions and not the whole data.
  3. Lookup frequency can be very large. Actually every SMS sent from the platform has to first make a lookup against the data (DND). So if the platform is handling 100 sms per second, it has to make 100 lookups per second against this data. The lookup simply checks existence of a particular mobile number against the data(DND) in database.
  4. The new delta data dump (additions / deletions), has to be synced in few hours only, as the dump is provided by telecom authority in the day and the same has to go live by midnight 00:00 hours. So the total time to sync data will be around 3 hours.

Sample DND dump

Sample of DND dump provided. Here A under Opstype means record has to be added, while as D means record has to be deleted.

Sample of DND dump provided. Here A under Opstype means record has to be added, while as D means record has to be deleted.

29 Dec
3 years ago

ehsanquddusi started a new conversation Condition On Eloquent Relation

I have Eloquent Model Coupons with belongsTo relationship with Customers model. I want to get all coupons created today where customer has not been created today.

Coupon::whereHas('customer', function($q) {
                    $q->where(DB::raw('DATE(`created_at`)'), '<>', date('Y-m-d'));
                })
                ->where(DB::raw('DATE(`created_at`)'), '=', date('Y-m-d'))
                ->count()

With valid data in db, it is still showing count as 0. Please help in fixing it.

20 Dec
3 years ago

ehsanquddusi left a reply on Server Without Internetconnection

Laravel will work as a standalone application without internet requirement. There will be absolutely no issues unless you are using some services which may require internet access.

ehsanquddusi left a reply on How To Bind Parameters To A Raw Query?

It has to be

$this->select('name',
     DB::raw("(
        SELECT  COUNT(id)
        FROM    test 
        WHERE   mid = :member AND created > :from AND created < :to
        ) as numbers", ["member" => $member, "from" => $from, "to" => $to])
)
->where('id', '=', '5')
->groupBy('type');

Notice the array passed with values. It has to be without :

15 Dec
3 years ago

ehsanquddusi left a reply on Generate Large Number Of Unique Coupons (~6 Characters)

@Tavicu - That is practically not possible. It will lead to memory leaks. What if we have ~1000000 promo codes in db?

13 Dec
3 years ago

ehsanquddusi left a reply on Move /public Into A Sub Directory

Check the permissions with your installation, especially storage. Most of the times, the 500 issue is because of permission issues. You need to have write permissions on this directory.

ehsanquddusi left a reply on Generate Large Number Of Unique Coupons (~6 Characters)

@jimmy.puckett - Thanks.

But I need to check the uniqueness in existing promo codes (which are in db). Any solution for that.

ehsanquddusi started a new conversation Generate Large Number Of Unique Coupons (~6 Characters)

I need to create promo codes which should be short in length (~ 6 characters). The promo codes have to be unique, so I need to check their uniqueness in database as well. They need to be generated in batches of thousands, so a check in db with every coupon generation is not feasible. I have created a method which first generates the required number of coupons and then check for duplicates using where in(). Having duplicate count of greater than zero, makes it generate the count again.

    public function generateCoupons($count, $length = 6)
    {
        $coupons = [];
        while(count($coupons) < $count) {
            do {
                $coupon = strtoupper(str_random($length));
            } while (in_array($coupon, $coupons));
            $coupons[] = $coupon;
        }

        $existing = Offer::whereIn('coupon', $coupons)->count();
        if ($existing > 0)
            $coupons += $this->generateCoupons($existing, $length);

        return (count($coupons) == 1) ? $coupons[0] : $coupons;
    }

Need suggestions how to improve upon this? Or if I can have some other way to achieve the same.

13 Nov
3 years ago

ehsanquddusi left a reply on Confused About Lookup Tables

@phpMick - This is only when you have Many to Many relation between managers & users. Means a manager can have multiple users and a user can have multiple managers. If this is the case, then the approach is correct, only thing is that laravel has a standard naming convention that you can follow.

managers - id, name
users - id, name
manager_user - manager_id, user_id

Then the corresponding models will be

class Manager extends Eloquent
{
    public function users()
         {
            return $this->belongsToMany(User::class);
         }
}

class User extends Eloquent
{
        public function managers()
        {
            return $this->belongsToMany(Manager::class);
        }
}

ehsanquddusi left a reply on Confused About Lookup Tables

@phpMick - You can simply get all the users of a manager using

$users = Manager::find($id)->users;

Or you can find manager of a particular user by using $manager = User::find($id)->manager;

ehsanquddusi left a reply on Confused About Lookup Tables

There can be either One to One relationship between Users & Managers or One to Many or Many to Many.

You will need to define the relationship in User model as well as in Manager model. As you have mentioned users instead of user, I suppose it will be One to Many between Manager and Users. In that case it will look like.

class Manager extends Eloquent
{
    public function users()
         {
            return $this->hasMany(User::class);
         }
}

class User extends Eloquent
{
        public function manager()
        {
            return $this->belongsTo(Manager::class);
        }
}

ehsanquddusi left a reply on Efficient Way To Replace Placeholders In A String Using Eloquent Object

One solution I found was to lazy eager load the relations using

$member->load('district', 'profession');

ehsanquddusi left a reply on Eloquent Sync Relations Question

Try

$post->comments()->delete();
$post->comments()->saveMany($comments);

ehsanquddusi left a reply on Job Not Queued

Oops! I was using sync. Had forgotten to set in my environment. Thank you for pointing out @XSkinner

ehsanquddusi started a new conversation Efficient Way To Replace Placeholders In A String Using Eloquent Object

I have an Eloquent class Member with relationships defined as District, Profession

An instance of Member class can be passed to a method which replaces placeholders from a string using this instance.

The placeholders are of format %placeholder%, where placeholder can be either an attribute of Member class or an attribute from its relation using dot notation like %name%, %district.name%

The problem I face is that I get Member instance without relations eager loaded.

So I have to reload the instance like this.

$member = Member::with(['district', 'profession'])->find($member->id);

Then I replace the placeholders using this syntax.

$member = $member->toArray();
$placeholders = array_keys($member);
foreach($placeholders as &$placeholder) {
    $placeholder ='%'.$placeholder.'%';
}
$finalString = str_replace($placeholders, array_values($member), $string);

Please guide whether I am doing it efficiently or there is some other way to achieve this. Especially I don't want to make another db call to eager load relations so that they can be converted to array.

ehsanquddusi started a new conversation Job Not Queued

I am firing an event from my controller. My event listener implements ShouldQueue contract.

The listener sends sms notification which is not queued at all and is fired immediately.

I am not running queue listener at all.

Please note that I am checking this on Windows machine, which I feel should queue the job.

My listener class is

class SmsMemberInfo implements ShouldQueue
{
    protected $sms;
   
    public function __construct(SMS $sms)
    {
        $this->sms = $sms;
    }

   public function handle(MemberAdded $event)
    {
            $template = 'Hello Testing';
            $this->sms->send($template, $event->member->mobile);
        }
    }
}
11 Nov
3 years ago

ehsanquddusi left a reply on I'm Trying To Traverse Through Complex Eloquent Model Relationships/attributes, And I'd Like To Use A Simple Dot Structure To Iterate Through This, Similar To How You Can Traverse Arrays With `Arr::get()` Example: $data = [ 'foo' => [

There is a collect helper to convert your array into Collection Simply call

$data =collect( [
  'foo' => [
    'bar' => [
      'key' => 'value'
    ]
  ]
]);
$value =$data->get('foo.bar.key'); // returns 'value'

You will get all the methods of Collection class available with your $data object.

10 Nov
3 years ago

ehsanquddusi left a reply on Laravel Eloquent JOIN AND SELECT MAX ROW

Replace DB with your model to use eager loading.

ehsanquddusi left a reply on Help Me Fix This Query Please :/

Check the query generated by eloquent using toSql() method. Also check whether the user is logged in and a valid id is returned by Sentinel::getUser()->id

$searchText = $request->input('search'); // get the search text

        $user = User::with([ // get logged in user and all relevant data
            'dealer' => function ($query1) use ($searchText) {

                $query1->with([
                    'customers' => function ($query2) use ($searchText) {
                        $query2->where('first_name', 'Like', '%$searchText%')
                        ->orwhere('last_name', 'Like', '%$searchText%')
                        ->orwhere('email', 'Like', '%$searchText%')
                        ->orderBy('created_at', 'asc');
                    }
                ]);
            },
            'dealer.customers.billingAddress.getCountry',
            'dealer.customers.billingAddress.getCounty',
            'dealer.customers.shippingAddress.country',
            'dealer.customers.shippingAddress.county',
            'dealer.customers.registeredProducts.product'
        ])->where('id', Sentinel::getUser()->id)->toSql();

ehsanquddusi left a reply on Return Redirect From Within Another Method In Controller

@squigg - Thank you for your suggestion. I am trying to figure out how to use Laravel Authorization with my current setup. Please guide for the same https://laracasts.com/discuss/channels/laravel/using-rolespermissions-with-laravel-authorization