jlrdw

jlrdw

Member Since 3 Years Ago

Experience Points 299,630
Experience Level 50

0 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 96
Lessons
Completed
Best Reply Awards 301
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.

25 Mar
1 day ago

jlrdw left a reply on Laravel Constructor - How To Use It Correctly?

I am just trying to understand the best use of a constructor.

Use for things that apply every time the class is called:

As example from docs:

public function __construct()
{
    $this->middleware('auth');
}

Would apply to all methods:

jlrdw left a reply on How To Find Laravel Engineer Practical Test Documents?

@BOBBYBOUWMANN - I think @msoft is saying he wants to be a Laravel Engineer already.

jlrdw left a reply on How To Convert A Associative Array To A 2 Dimensional Array

Start with the keys, example $quy is your array

$keys = array_keys($quy);
for ($i = 0; $i < count($quy); $i++) {
          foreach ($quy[$i] as $key => $value) {
          // here work out what you need to do

Can take some trial and error.

jlrdw left a reply on Storing Date/Time As UTC, Problem With Daylight Savings Time

Also if you need to store dates as Central Time Zone get them as central time zone, store them a central time zone don't even mess with utc for appointments.

Ditto for other use of time zones.

jlrdw left a reply on Storing Date/Time As UTC, Problem With Daylight Savings Time

Time zone has nothing to do with it. An appointment at 2 p.m. on a certain day will not change unless the Law changes when time zones are set again.

If you set an appointment that's 2 p.m. store in UTC and retrieve UTC and convert back to Central Time for display all will be correct.

jlrdw left a reply on Storing Date/Time As UTC, Problem With Daylight Savings Time

I was referring to physically changing a time zone. If I have an appointment in Dallas Texas on a certain date at 2 p.m. that's where the appointment will be I won't be flying to London for the appointment.

jlrdw left a reply on Storing Date/Time As UTC, Problem With Daylight Savings Time

creates an appointment for 2pm

Just store a date time for an appointment in user timezone. If a set appointment, no conversion should be needed.

jlrdw left a reply on Converting A Complex Sql Query To Query Builder

This has been asked over and over.

And eloquent query or QB is something like:

$quy = Powner::query()->leftJoin('dc_pets', 'dc_powners.ownerid', '=', 'dc_pets.ownerid')
                ->select('dc_powners.ownerid', 'dc_powners.oname')->distinct()
                ->selectRaw('max(dc_pets.petid) as maxPetId')
                ->where('dc_powners.ownerid', '<', 3)
                ->groupby('dc_powners.ownerid')
                ->orderby('dc_powners.oname')
                ->get();

OR use relations:

https://laravel.com/docs/5.8/eloquent-relationships

OR use as is:

https://laracasts.com/discuss/channels/laravel/sql-native-to-query-builder

Use some trial and error to work out the exact query.

24 Mar
2 days ago

jlrdw left a reply on Inventory Handling

Dealing with inventory, and the handling really isn't a topic to learn in a quick forum answer. There are thick books on the subject.

But years ago, late 1980's, when I dealt with inventory and supply in dbase 3, You learn how to set certain flags in your system.

If Joe orders a widget, bake order, their needs to be some sort of flag, relation, and event that tells the system, okay widgets came in, supply level is now 100%. Now fulfill back orders and current orders, then update inventory levels to current percent in stock..

It will take a little coding.

There are existing ordering systems on Github, could you not study over and get an idea how others handle it for shopping carts.

jlrdw left a reply on Model Policy Impacting Nova Edit Functionality

At some place you have to check if the Auth::user() is an admin, and program the logic accordingly. Usually with an if - else construct.

In my case, I actually have things the admin can view, but not edit (accounting stuff).

jlrdw left a reply on Laravel Access Denied For User 'root'@'localhost' Sometimes ?

Are the db values coming from env file, can you show what you have, star the PW.

jlrdw left a reply on Laravel Access Denied For User 'root'@'localhost' Sometimes ?

Do you have 2 installs of MySql, many times this is the problem.

jlrdw left a reply on Laravel Query In Database

Here is a join group by I used as example that works:

$quy = Powner::query()->leftJoin('dc_pets', 'dc_powners.ownerid', '=', 'dc_pets.ownerid')
          ->select('dc_powners.ownerid', 'dc_powners.oname')->distinct()
          ->selectRaw('count(dc_pets.petid) as countOfPets')
          ->groupby('dc_powners.ownerid')
          ->orderby('dc_powners.oname')
          ->get();

It gives a pet owner and count of their pets only:

Like

owner   |   countOfPets

john     2
mary    6

Have you tried a left join. Sometimes these queries require some trial and error to work out.

As example see: https://laracasts.com/discuss/channels/eloquent/orderby-computed-related-attribute

How even with assistance, it took time to work out.

Also have you considered using eloquent relations:

https://laravel.com/docs/5.8/eloquent

https://laravel.com/docs/5.8/eloquent-relationships

Just keep in mind, eloquent queries and even complex normal queries can take some playing around with to get right.

jlrdw left a reply on Trying To Get Property Of Non-object In Blade @if()

That all looks right, dou you have an auth()->user()->username?

Try to dd auth()->user()->username and see what happens.

jlrdw left a reply on What Is Laravel Repository Design Patten?

@bestmomo has an entire example laravel app with that pattern:

https://github.com/bestmomo/laravel5-5-example

jlrdw left a reply on Can't Force Laravel To Href Link Should Be From Root

Of course it's trying to href to your site. For an external link you just use the link:

<a href="https://laracasts.com">laracast test</a>
23 Mar
3 days ago

jlrdw left a reply on Acces To Adminpanel Via Permission "can_access_adminpanel" Or Role "admin"? Whats Better?

Generally there are several ways to deal with roles, permissions, etc.

I just have a role fields added to the user table, but it can contain multiple roles.

For example:


   roles 
-------------
admin
bkeep  // for bookkeeper
admin,bkeep   // both roles
user

I check if a role is matched via an array:

    
        $role = $user->role;
        $checkrole = explode(',', $role);
        if (in_array('admin', $checkrole)) {
            // do whatever
        } else {
           // whatever else
        }
   

That's just for an admin, other roles I handle a little different.

I work with the roles and verify a role matches a controller.

For example in the accounts controller for one method I have:

public function accounts()
    {
Cln::chklog('bkeep');
// more

Rather than having all kinds of can, cannot, etc, I wrote a class that handles laravel Auth in the background.

It checks like above if bkeep in one of the roles of the logged in user. If so no problem, if not, access is not granted. I just like handling it on each controller like that.

In your case, and if a very secure app, you could do both.

Permissions is more for can an admin for example edit things in bookkeeping.

Usually no, they can view. That's where queries come in.

Queries that allows a bookkeeper to completely add, edit, etc. But a query is needed for admin to view the data only.

Some people write one view, with if - else -can -cannot - etc Meaning for bookkeeper you have your edit links. For admin no edit links.

But, and this is just me, by time you have all those if - else -can -cannot - etc which can become a mess, I pefer to have a separate controller methods and separate views for bookkeeper and admin.

So I check roles, and let permissions take care of themselves in the query.

  • admin can view and edit any post
  • user can only view and edit their post

So a query without the where user_id for admin

a query with the where user_id for user.

This has to be done anyway, so by checking role, and permissions can or don't have to be used.

It depends on how well you work with the roles.

jlrdw left a reply on External Url Content To Laravel

Can't you use an iframe.

jlrdw started a new conversation Manual Pagination Episode 3

A question came up how to paginate using the DB Facade. And since at times it's used instead of query builder or eloquent, here goes:

  • You have to have a count of results.

And just a simple example:

    public function indexdb()
    {
        $page = !empty(Request::input('page')) ? Request::input('page') : '1';
        $search = !empty(Request::input('search')) ? Request::input('search') : '';
        $sch = $search . "%";
        $perpage = "5";
        $offset = ($page - 1) * $perpage;
        $krows = DB::select('SELECT COUNT(dogid) as total FROM dc_dogs WHERE dogname LIKE :search', [':search' => $sch]);
        $numrows = $krows[0]->total;
        $pagingQuery = "LIMIT {$offset}, {$perpage}";
        $quy = DB::select("SELECT * FROM dc_dogs WHERE dogname LIKE :search " . $pagingQuery, [':search' => $sch]);
        $dogs = new LengthAwarePaginator($quy, $numrows, $perpage);
        $qs = ['search' => $search, 'page' => $page];
        $title = 'Dogs';
        return view('dog.indexg', compact('dogs', 'title', 'qs'));
        }

And in the view:

@php echo str_replace('/?', '?', $dogs->appends($qs)->render('custompager')) @endphp

Here is an example of a more complex query using the DB Facade.

https://laracasts.com/discuss/channels/laravel/sql-native-to-query-builder

Of course have the proper use statements at top.

use Illuminate\Support\Facades\DB;
use Illuminate\Pagination\LengthAwarePaginator;

jlrdw left a reply on Count Another Table Row

$data = App\table1::withCount('color')->get();

 foreach ($data as $row) {
     echo $row->count . "-" . $row->color;
 }

Something like that, play around with it. But your relations have to be setup.

Work the example one to many in the docs, and Jeffrey has a one to many demo in his free video.

jlrdw left a reply on Pagination And Sortby

Have you tested paginating with a group by without

    if ($request->ajax()) {
        switch ($request->SortbyList) {
            case 0:
                $productsQuery = $productsQuery->orderBy('ratings_average', 'DESC');
                break;
            case 1:
                $productsQuery = $productsQuery->orderBy('ratings_average', 'ASC');
                break;
            case 2:
                $productsQuery = $productsQuery->orderBy('productname', 'ASC');
                break;
            case 3:
                $productsQuery = $productsQuery->orderBy('productname', 'DESC');
                break;
            default:
                $productsQuery = $productsQuery->orderBy('ratings_average', 'DESC');

        }
    }
    else{
        $productsQuery = $productsQuery->orderBy('ratings_average', 'DESC');


To see if the paginator works:

From the docs:

Currently, pagination operations that use a groupBy statement cannot be executed efficiently by Laravel. If you need to use a groupBy with a paginated result set, it is recommended that you query the database and create a paginator manually.

jlrdw left a reply on Count Another Table Row

Yes, many, may ways to do it.

As an example:

$quy = Powner::select('dc_powners.ownerid', 'dc_powners.oname')
          ->selectRaw('count(dc_pets.petid) as countofPetid')
          ->leftJoin('dc_pets', 'dc_powners.ownerid', '=', 'dc_pets.ownerid')
          ->groupby('dc_powners.ownerid')
          ->orderby('dc_powners.oname')
          ->get();

Just an example eloquent query.

It return data like

oname  | countofPetid

John  3
mary  7

But as above, you may be better of setting up relationships.

jlrdw left a reply on Trouble With Pagination With Collection

Same way you do in a collection except you just get so many results at a time.

Many of these things take some trial-and-error to get exactly right there's no one shot quick answer.

But eloquent relations can be paginated, many people do it all the time.

You may need to do a search on paginating eloquent relationships.

jlrdw left a reply on Pagination And Sortby

The case has to be in the query string and you going to need links on The View page.

In the link you have to pass the updated or new case and of course re load the page.

I would imagine if changing case you are probably going to start all over again with the pagination.

To get what you want I think you're going to need something like data tables where you can change the sort on the Fly.

jlrdw left a reply on DB::Select Query With Pagination ?

Use the skip and take and possible a Length aware Patinator

$dogs = DB::table('dc_dogs')
                        ->where('adopted', '=', 0)
                        ->skip($offset)->take($perpage)->get();
        $pagelinks = LengthPager::makeLengthAware($dogs, $numrows, $perpage, ['t1' => $t1]);

see https://laracasts.com/discuss/channels/guides/length-aware-paginator

jlrdw left a reply on Pagination And Sortby

You probably need to show more of your code: You are:

if ($request->ajax()) {

yet

return view('partials.search')....

How is this ajax pagination.

jlrdw left a reply on Trouble With Pagination With Collection

See https://laracasts.com/discuss/channels/guides/length-aware-paginator

It's redundant paginating a collection, unless you only have a small amount of results.

Just paginate the query.

22 Mar
4 days ago

jlrdw left a reply on Session Expires But Nav Bar Doesnt Update To Reflect

That's expected Behavior no different than if you were on a page that required authorization.

You can probably catch the error and redirect to a friendly page with a link to go back to login page.

jlrdw left a reply on How To Remove Item From Cart Through Session Laravel 5.6?

You put in a temp array, remove item, then rewrite to session.

$tmp = Session::get('yoursession'); 

unset($tmp[$key]); 

Session::set('yoursession', $tmp);

Not tested, on mobile now.

But something close to that should work.

jlrdw left a reply on Where To Use Vue In Laravel

Vue being a front end technology, you really need to take some tutorials.

where to use vue in laravel

Same place basically as HTML.

21 Mar
5 days ago

jlrdw left a reply on Laravel Ajax - Put Request 500 Internal Server Error

Glad you got it.

I may save a link to this post to help folks in future who have similar question. Easier than going over it again.

Yours is a more advanced example.

jlrdw left a reply on Laravel Ajax - Put Request 500 Internal Server Error

See my edited answer, you don't need to post using json.

jlrdw left a reply on Laravel Ajax - Put Request 500 Internal Server Error

In an ajax demo I did, i am only doing 2 fields, just simple demo:

<script>
    $(function () {
        $("#postjq").click(function (event)
        {
            event.preventDefault();
            var $post = {};
            $post.petid = $('#petid').val();
            $post.species = $('#species').val();
            $post.ocheck = ($("#ocheck").prop("checked") == true ? '1' : '0');
            $post._token = document.getElementsByName("_token")[0].value
            $.ajax({
                url: 'petupdate',
                type: 'POST',
                data: $post,
                cache: false,
                success: function (data) {
                    alert('Your data updated');
                    return data;
                },
                error: function () {
                    alert('error handing here');
                }
            });
        });
    });

And I just used a simple route:

Route::put('petupdate', array('uses' => '[email protected]'));

I know not real advanced, but that works.

Are you sure everything is loaded. Do an alert in the JS to ensure it's working.

But from what you said it is.

jlrdw left a reply on Laravel Ajax - Put Request 500 Internal Server Error

Did you clear temp views, all cache, browser cache, etc. Give me a minute or so also.

jlrdw left a reply on Laravel Roles

A follow up:

Warning, not a laravel example

But something similar I am currently working on in an app I am migrating:

Take a record that's going to be edited:

$data['row'] = $this->Pet->getPet($petid);
Cln::chkUserId($data['row'][0]->owner_id);

And a method to make sure the logged in user owns that record:

    public static function chkUserId($userid)
    {
        if ($userid === Session::get('owner') || Session::get('isadmin') === 'admin') {
            return;
        } else {
            Url::redirect('admin/admin'); // or where ever
        }
        return false;
    }

But this should never get hit. The only time it would if the user manually places an id in the url.

jlrdw left a reply on Laravel Roles

How are you supposed to expose certain parts of a view based on a user's permissions

As said, for user an index method, for admin, an indexadmin method. Two different views.

I didn't say I never do it in the view, I try to avoid if I can.

For user to see and edit there own data only, that can be checked in the controller.

jlrdw left a reply on Best Way To Have Multiple "child" Jobs Update A "parent" Job/model Status When All Have Completed?

@MATT.LIBERA - Jeffrey's search is not a powerful as google. For google

site:laracasts.com your search term

jlrdw left a reply on Handling User Permissions

I have no idea if this would even apply to Vue, but there is a current roles post happening right now. Would hurt to look it over.

https://laracasts.com/discuss/channels/laravel/laravel-roles-1