Zaheer

Zaheer

Member Since 2 Months Ago

Experience Points 770
Experience Level 1

4,230 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 1
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    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 Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

19 Jul
3 days ago

Zaheer left a reply on Left Join Within A Left Join

Found the solution. Correct query is :

$query = DB::table('autostk')
    ->where('autostk.branchid', $branch_id)
    ->where('autostk.itemcode',$request->itemcode)
    ->whereDate('autostk.date','<=',$request->tdate)
    ->leftjoin('journal AS j', function($join) use ($branch_id) {
        $join->on('autostk.refno', '=', 'j.vno')
        ->on('autostk.vtype', '=', 'j.vtype')
            ->where('j.code', '>=', 100)
            ->where('j.branchid', $branch_id)
            ->leftjoin('accounts', 'j.code', '=', 'accounts.code')
            ->where('accounts.branchid', $branch_id);
    })
    ->select('j.code','accounts.title','autostk.*')
    ->orderBY('date')->get()
    ->map(function ($item, $key) {
        return (array) $item;
    })
    ->all();

Zaheer started a new conversation Left Join Within A Left Join

Can someone help fix this query. I am getting "null" result for "j.code" and "accounts.title" which should have a value. Is this the proper way of using left join within a left join. Here is my query :

$query = DB::table('autostk')
    ->where('autostk.branchid', $branch_id)
    ->where('autostk.itemcode',$request->itemcode)
    ->whereDate('autostk.date','<=',$request->tdate)
    ->leftjoin('journal AS j', function($join) use ($branch_id) {
        $join->on('autostk.refno', '=', 'j.vno')
            ->where('j.code', '>=', 100)
            ->where('j.branchid', $branch_id)
            ->where('j.vtype', '=', 'autostk.vtype')
            ->leftjoin('accounts', 'j.code', '=', 'accounts.code')
            ->where('accounts.branchid', $branch_id);
    })
    ->select('j.code','accounts.title','autostk.*')
    ->orderBY('date')->get()
    ->map(function ($item, $key) {
        return (array) $item;
    })
    ->all();

The raw query being generated is :

select `j`.`code`, `accounts`.`title`, `autostk`.* from `autostk`
left join (`journal` as `j` left join `accounts` on `j`.`code`=`accounts`.`code`)
on `autostk`.`refno` = `j`.`vno` and `j`.`code` >= ? and `j`.`branchid` = ?
and `j`.`vtype` = ? and `accounts`.`branchid` = ? where `autostk`.`branchid` = ?
and `autostk`.`itemcode` = ? and date(`autostk`.`date`) <= ? order by
`autostk`.`date` asc
12 Jul
1 week ago

Zaheer left a reply on Add New Column/element To Collection

Yes I understand and this is what I am looking for. What i want to do, is retrieve data from the database. Add some calculated columns and generate a report. Thank you very much for your time and support.

Zaheer left a reply on Add New Column/element To Collection

This does add clbal to $getacc but not to $acc. I am new to laravel and eloquent is not fully clear to me. What I figured out is that i am on the wrong track. I am trying to use laravel collection as an array, which I think is not possible. I need to first convert collection data to array and then I will be able to add columns and change values without affecting the database. Hope I am right this time.

Zaheer left a reply on Add New Column/element To Collection

I dont want to add the column to database. the column is needed temporarily for reporting purpose only.

Zaheer left a reply on Add New Column/element To Collection

From your given link. I tried this :

foreach ($rslt as $row) {
    $getacc = $acc->where('code',$row->code)->first();
    $getacc->map(function($item) use ($row) {
        $item['clbal'] = $row->total;
        return $item;
    });
}

This give me "Call to undefined method App\Accounts::map()"

Zaheer left a reply on Add New Column/element To Collection

Can I set a default value to the column upon adding ? Can you share how can I add the column

Zaheer left a reply on Add New Column/element To Collection

I dont want to add this column to database, it is temporarily required. Is it possible to add the column to collection only.

Zaheer left a reply on Add New Column/element To Collection

This gives an error "Unknown column clbal"

Zaheer started a new conversation Add New Column/element To Collection

I can update a collection with following code :

foreach ($rslt as $row) {
    $getacc = $acc->where('code',$row->code)->first();
    $getacc->update(['clbal' => $row->total]);
}

This requires that clbal column must be present in $getacc. What if I want to add this column to collection. Is there any Insert() function available.

Zaheer left a reply on How To Do This Query In Eloquent

Thanks alot.

Zaheer started a new conversation How To Do This Query In Eloquent

Can someone convert this mysql query to Laravel eloquent :

SELECT * FROM journal where code in (select code from accounts where type=1 or type=3);

I tried this but it gives me "Call to undefined method App\Journal::code()"

$rslt = Journal::where('journal.branchid', $branch_id)
     ->whereHas('code', function($query) {
       $query->where('code', '=', \Accounts::input('code')->whereIn('type',[1,3]));})
     ->where(function($q) {$q->where('journal.cancel','!=',1)->orWhereNull('journal.cancel');})
     ->select('code',DB::raw('sum(IFNULL(dr,0) - IFNULL(cr,0)) as total'))->groupBy('code')->Get('code','total');

Zaheer left a reply on Find And Replace In Laravel Collection

Sorry for that. Its done now.

11 Jul
1 week ago

Zaheer left a reply on Find And Replace In Laravel Collection

Excellent !!!! Changing "DB::table('accounts')" to "Account::..." worked. Thanks for pointing out.

Zaheer left a reply on Find And Replace In Laravel Collection

Thanks for reply.

For the save() option I am getting this error : Object of class stdClass could not be converted to string

and for update() : Call to undefined method stdClass::update()

Zaheer started a new conversation Find And Replace In Laravel Collection

I am trying to update a laravel collection with another collection. Here are my collections :

$acc = DB::table('accounts')
    ->where('accounts.branchid', $branch_id)
    ->select('code','title','opbal','clbal')->get();
$rslt = DB::table('journal')
    ->where('journal.branchid', $branch_id)
    ->where(function($q) {$q->where('journal.cancel','!=',1)->orWhereNull('journal.cancel');})
    ->select('code',DB::raw('sum(IFNULL(dr,0) - IFNULL(cr,0)) as total'))->groupBy('code')->Get('code','total');

What I want is to update $acc->clbal with $rslt->total where $acc->code = $rslt->code I tried this but it does not work

foreach ($rslt as $row) {
    $getacc = $acc->where('code',$row->code);
    $getacc->clbal = $row->total;
}
28 May
1 month ago

Zaheer started a new conversation DB::transactions Failed Or Succeeded

How do I know if a transaction failed or succeeded. If it failed what was the error ? While searching I found that it can be done "listening to connection.rollingback". How can I listen to this event ? Help with some sample code or useful links will be highly appreciated.

25 May
1 month ago

Zaheer left a reply on Relation Not Working

This query returns 'title' column with null value

    public function title()
    {
        $branch_id=session()->get('lbranch','0');
        return $this->hasOne('App\Accounts','code','supp_code')
            ->select('title')->where('branchid','=',$branch_id);
    }

Zaheer left a reply on Cannot Display Date

I am new to web development and Laravel. Was unable to understand Carbon. Ended up using Moment.js

$('#date').val(moment(data.invoice.date).format("YYYY-MM-DDTHH:mm"));

Zaheer left a reply on Relation Not Working

I have changed my Model code to :

    public function title()
    {
        $branch_id=session()->get('lbranch','0');
        return $this->hasOne('App\Accounts','code','supp_code')
            ->where('branchid','=',$branch_id);
    }

Now I am getting all columns from Accounts model in 'title' as an object. How can I get only title column ? I tried this but it throws an error :

        return $this->hasOne('App\Accounts','code','supp_code')
            ->where('branchid','=',$branch_id)->get('title');

Zaheer left a reply on Cannot Display Date

@SNAPEY - It throws following error : LOG.error: Call to a member function format() on string {"userId":161,"exception":{}}

My model code is as under : (have i done it right ?)

class Purchase extends Model
{
    //
    protected $guarded = [];
    protected $appends = ['formattedDate'];

    public function getFormattedDateAttribute()
    {
    return $this->date->format('Y-m-d\TH:i');
    }
}

Zaheer left a reply on Cannot Display Date

@JLRDW - Yes, it give me blank input element.

24 May
1 month ago

Zaheer left a reply on Cannot Display Date

@SNAPEY - THEN was ajax code and NOW is the supporting code. Ajax code is calling controller code to display result in Input element.

Zaheer left a reply on Cannot Display Date

@SNAPEY - I am getting this value from data.invoice['date'] 2019-05-23 16:05:00

and my controller code is :

        $invoice = Purchase::find($id)->toArray();
        $items = Purchase::find($id)->items->toArray();
        return response()->json(array('invoice'=>$invoice,'items'=>$items));

Zaheer started a new conversation Cannot Display Date

I am using following code to display a datetime value from mysql table to a datetime-local input element.

$('#date').text(data.invoice['date'].toString('Y-m-dTH:i'));

But instead of showing date from table it is displaying current date. What I am doing wrong ?

Zaheer left a reply on Relation Not Working

Laravel documentaion says :

You may query the posts relationship and add additional constraints to the relationship like so:
$user = App\User::find(1);
$user->posts()->where('active', 1)->get();

I changed my Model code to :

        return $this->hasOne('App\Accounts','code','supp_code');

and controller code :

           $data = Purchase::where('purchases.branchid',$branch_id)
               ->select('purchases.*',
                   DB::raw('(CASE 
                        WHEN purchases.posted = "1" THEN "Posted" 
                        ELSE "Unposted" 
                        END) AS status'))
               ->latest()->get();

           $data->title()->where('branchid',$branch_id)->get();

but I am getting error : [11:43:01] LOG.error: Method Illuminate\Database\Eloquent\Collection::title does not exist. {"userId":161,"exception":{}}

Zaheer left a reply on Relation Not Working

@SNAPEY - Here are the queries :

select `purchases`.*, (CASE WHEN purchases.posted = "1" THEN "Posted" ELSE "Unposted" END) AS status from `purchases` where `purchases`.`branchid` = 22 order by `created_at` desc

select * from `accounts` where `branchid` is null and `accounts`.`code` in (100)
23 May
1 month ago

Zaheer left a reply on Relation Not Working

@SNAPEY - Thanks for a quick reply. But its still not working.

Zaheer started a new conversation Relation Not Working

Can someone help me why I am getting blank result. My Model relation :

    public function title()
    {
        return $this->hasOne('App\Accounts','code','supp_code')->where('Accounts.branchid','=','Purchases.branchid');
    }

My Controller :

           $data = Purchase::with('title')
               ->where('purchases.branchid',$branch_id)
               ->select('purchases.*',
                   DB::raw('(CASE 
                        WHEN purchases.posted = "1" THEN "Posted" 
                        ELSE "Unposted" 
                        END) AS status'))
               ->latest()->get();

I am getting null for the 'title' column. Thanks in advance.

19 May
2 months ago

Zaheer started a new conversation Need Help In Saving Invoice Data

I have a standard invoice with header info and multiple products in an html table. Can save header information but cannot figure out how to save the products. I am using a Modal form with Ajax to send data to Controller. My Ajax code is as under :

            $('#saveBtn').click(function (e) {
                e.preventDefault();
                $(this).html('Sending..');
                var tbldata = tbltoarr();
                $.ajax({
                    data: $('#purchaseForm').serialize(),
                    url: "{{ route('purchases.store') }}",
                    type: "POST",
                    dataType: 'json',
                    success: function (data) {
                        $('#purchaseForm').trigger("reset");
                        $('#code').focus();
                    },
                    error: function (data) {
                        var data2 = JSON.parse(data.responseText);
                        $('.alert-danger').html('');
                        jQuery.each(data2.errors, function(key, value){
                            jQuery('.alert-danger').show();
                            jQuery('.alert-danger').append('<li>'+value+'</li>');
                        });
                    }
                });
            });

and Controller code is :

 public function store(Request $request)
    {

$result = Purchase::updateOrCreate(['id' => $request->id],
    [   'date' => $request->date,
        'suppcode' => $request->code,
        'suppinv' => $request->invno,
        'suppdate' => $request->invdate,
    ]);

        return response()->json(['success'=>'Account saved successfully.']);
    }

tbldata is an array of items added to invoice, with following columns : Itemcode,Itemdesc,qty,rate,amount My question is how to attach tbldata to ajax post request and then how to handle/save it in controller.

12 May
2 months ago

Zaheer left a reply on Failed Ajax Call To Datatables. Returns 404 Not Found

No login is not a problem. The problem exists even when I remove it.

Zaheer started a new conversation Failed Ajax Call To Datatables. Returns 404 Not Found

I am getting a DataTables warning: table id=DataTables_Table_0 - Ajax error. Correct data is returned most of the times but once every three or four calls this Warning appears with no data loaded in data tables. Can someone identify what is wrong with my code. I am a beginner in web development.

Upon debugging I found that no call to controller is sent when this warning appears. The console says 404 Not found. I think it is the route not found. But then why it is loading most of the times. I have also put a Info($request) in the controller, and Laravel log is empty when this error appears.

I am using Laravel 5.8. HTML code is :

    <div class="box-body">
        <table class="data-table display compact">
            <thead>
            <tr>
                <th width="50px">Action</th>
                <th>Date</th>
                <th>Ref. No.</th>
                <th>Supplier</th>
                <th>Inv. No.</th>
                <th>Inv. Date</th>
                <th>Total</th>
                <th>Freight</th>
                <th>Discount</th>
                <th>Cash</th>
                <th>Net Total</th>
                <th>Remarks</th>
                <th>Status</th>
            </tr>
            </thead>

            <tbody>

            </tbody>
        </table>
    </div>

Ajax code is :

            var table = $('.data-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: "{{ route('purchlist') }}",
                columns: [
                    {data: 'action', name: 'action', orderable: false, searchable: false, width: "50px"},
                    {data: 'date', name: 'date'},
                    {data: 'refno', name: 'refno'},
                    {data: 'title', name: 'title'},
                    {data: 'sup_invno', name: 'sup_invno'},
                    {data: 'sup_invdate', name: 'sup_invdate'},
                    {data: 'total', name: 'total'},
                    {data: 'freight', name: 'freight'},
                    {data: 'discount', name: 'discount'},
                    {data: 'cash', name: 'cash'},
                    {data: 'nettotal', name: 'nettotal'},
                    {data: 'remarks', name: 'remarks'},
                    {data: 'status', name: 'status'},
                ]
            });

And my Controller code is :

    public function index(Request $request)
    {
        $branch_id=session()->get('lbranch','0');
        if ($branch_id==0){
            return redirect()->route('login');
        }

       if ($request->ajax()) {
            $data = DB::table('purchases')
                ->where('purchases.branchid',$branch_id)
                ->where('accounts.branchid',$branch_id)
                ->leftjoin('accounts','purchases.account_code','=','accounts.code')
                ->select('purchases.*',
                    DB::raw('(CASE 
                        WHEN purchases.posted = "1" THEN "Posted" 
                        ELSE "Unposted" 
                        END) AS status'),
                    'accounts.title')
                ->latest()->get();

            return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function($row){
                    $btn = '<a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$row->id.'" data-original-title="Edit" class="edit btn btn-primary btn-sm editPurchase"><i class="fa fa-edit"></i></a>';
                    $btn = $btn.' <a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$row->id.'" data-original-title="Delete" class="btn btn-danger btn-sm deletePurchase"><i class="fa fa-trash"></i></a>';
                    return $btn;
                })
                ->rawColumns(['action'])
                ->make(true);
        }
        return view('purchases',compact('purchases'));
    }