WallyJ

WallyJ

Member Since 1 Year Ago

Experience Points 4,000
Experience
Level
Lessons Completed 12
Lessons
Completed
Best Reply Awards 0
Best Answer
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.

08 Dec
3 days ago

WallyJ left a reply on Accessor Full_name Breaks AJAX Lookup

Thanks @cronix ! For the sake of my understanding, is there a specific reason you wouldn't use one of the other methods I mentioned?

07 Dec
4 days ago

WallyJ left a reply on Accessor Full_name Breaks AJAX Lookup

@realrandyallen , Thanks for the suggestion, though I received an error with your code concerning the }. Probably a syntax issue.

@cronix , I used your code and it worked perfectly. I had to add the additional last name to the "li" element so that the last name would show up in the list, but now it does.

The only issue I have now is that the search box only works on the Dashboard page (the controller code I gave).

Should I add the function from the Controller to a helper file if I want it available for all views (since it is in the nav bar of the app.blade.php file it will essentially be available almost everywhere)?

Or should I add it to something like common.php and use:

use Common

in every controller?

Now that it works, I don't want to break it again by making it globally available.

Thanks again!

WallyJ started a new conversation Accessor Full_name Breaks AJAX Lookup

The following code was working until I replaced "contact1firstname" (a single field in the db), with "full_name", an Eloquent Accessor that combines "contact1firstname" and "contact1lastname" for the sake of searching the combined fields rather than just the first name. Now when I type in my search box nothing happens.

Contact Model:

public function getFullnameAttribute()
    {
        return "{$this->contact1firstname} {$this->contact1lastname}";
    }

Controller:

public function fetch(Request $request)
    {
        $user_id = auth()->user()->id;
        if($request->get('query'))
        {
            $query = $request->get('query');
            $data = Contact::where('user_id', '=', $user_id)
            ->where('full_name', 'LIKE', '%'.$query.'%')
            ->get();
            $output = '<ul class="dropdown-menu" style="display:block; position:relative">';
            foreach($data as $row)
            {
                $output = '<li class="dropdown-item"><a href="#">' .$row->full_name. '</a></li>';
                echo $output;
            }
            $output = '</ul>';
        }
    }

View (Search Box and Script):

<ul class="nav navbar-nav mx-auto form-group" style="display:block; position:relative">
<li class="nav-item dropdown">
<input type="text" class="form-control" name="contactsearchBox" id="contactsearchBox" placeholder="Search">
</li>
<div class="dropdown-menu" aria-labelledby="navbarDropdown" id="contactList"></div>
{{ csrf_field() }}
</ul>

<script src="{{ asset('js/app.js') }}"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
    
    <script type="text/javascript">
        $(document).ready(function() {
            $('#contactsearchBox').keyup(function() {
                var query = $(this).val();
                console.log(query);                
                if (query !='')
                    {
                        $.ajaxSetup({
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                            }
                        });
                        $.ajax({
                            url:"{{ route('dashboard.fetch') }}",
                            method:"POST",
                            data:{
                                query : query 
                                // '_token': 'X-CSRF-TOKEN',
                                // _token : _token
                            },
                                success:function(data)
                                {
                                    $('#contactList').fadeIn();
                                    $('#contactList').html(data);
                                }
                            })
                        }
                    });
                $(document).on('click', 'a', function(){
                    $('#full_name').val($(this).text());
                    $('#contactList').fadeOut();
                });
            });
    </script>

I'm sure it's something I'm doing wrong with the Accessor, but I'm not sure what. Thanks!

16 Nov
3 weeks ago

WallyJ left a reply on 500 Internal Server Error - Submitting Form To Route Through Ajax

@TALINON - console.log(data) is not in the success method. console.log(query) is just after the query variable is declared so I can test it in the console to make sure the characters are being picked up as I type them, if that's what you mean.

WallyJ left a reply on 500 Internal Server Error - Submitting Form To Route Through Ajax

@CRONIX - Good word! I am also using the search box as part of a Bootstrap Navbar, so I'm having to rethink the formatting portion of my code, but that is a great fix to the loop portion. I want the search box to be in the center of the navbar at the top and the autocomplete search results to be directly below the search box. I want it in the navbar so it can be used on any page a user might be on.

WallyJ left a reply on 500 Internal Server Error - Submitting Form To Route Through Ajax

I changed my where line with the wildcard to :

->where('contact1firstname', 'LIKE', '%'.$query.'%')

And I am now getting results. Thanks all!

WallyJ left a reply on 500 Internal Server Error - Submitting Form To Route Through Ajax

@TALINON - Interestingly, after I removed the first get(), the 500 error went away, and the

console.log(query); 

line is sending the string to the console each time I type a character (used for testing), but the Autocomplete box seems to do nothing. So now I removed the error, but am only filling the "query" variable. The list of contacts is not showing.

WallyJ left a reply on 500 Internal Server Error - Submitting Form To Route Through Ajax

@JLRDW - With jQuery Autocomplete you don't need a complete form, just the form field itself, see https://jqueryui.com/autocomplete/

WallyJ started a new conversation 500 Internal Server Error - Submitting Form To Route Through Ajax

I have a JQuery Autocomplete that is throwing a 500 Internal Server Error as I type in the text field, and thought this may seem more like a JQuery or Ajax issue, I believe the problem lies in how Laravel is handling the CSRF token as part of the process. Here is my code (relevant parts):

Form in Blade:

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Styles -->
    
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    {{-- <link href="{{ asset('css/app.css') }}" rel="stylesheet"> --}}
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />

</head>
<body>

<div class="nav navbar-nav mx-auto form-group">
<input type="text" class="form-control" name="contactsearchBox" id="contactsearchBox" placeholder="Search">
<div id="contactList"></div>
{{ csrf_field() }}
</div>

<!-- Scripts -->
    <script src="{{ asset('js/app.js') }}"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
    
    <script type="text/javascript">
        $(document).ready(function() {
            $('#contactsearchBox').keyup(function() {
                var query = $(this).val();
                console.log(query);                
                if (query !='')
                    {
                        $.ajaxSetup({
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                            }
                        });
                        $.ajax({
                            url:"{{ route('dashboard.fetch') }}",
                            method:"POST",
                            data:{
                                query : query 
                                // '_token': 'X-CSRF-TOKEN',
                                // _token : _token
                            },
                                success:function(data)
                                {
                                    $('#contactList').fadeIn();
                                    $('#contactList').html(data);
                                }
                            })
                        }
                    });
                $(document).on('click', 'li', function(){
                    $('#contact1firstname').val($(this).text());
                    $('#contactList').fadeOut();
                });
            });
    </script>

    
</body>
</html>

Controller:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Profile;
use App\User;
use Auth;
use App\Contact;

public function fetch(Request $request)
    {
        $user_id = auth()->user()->id;
        if($request->get('query'))
        {
            $query = $request->get('query');
            $data = Contact::where('user_id', '=', $user_id)->get()
            ->where('contact1firstname', 'LIKE', '%{$query}%')
            ->get();
            $output = '<ul class="dropdown-menu" style="display:block; position:relative>';
            foreach($data as $row)
            {
                $output .= '<li><a href="#">' .$row->contact1firstname. '</a></li>';
                $output .= '</ul>';
                echo $output;
            }
        }
    }

I tried to follow the instructions found here - https://laravel.com/docs/master/csrf concerning the use of the CSRF token.

Thanks.

12 Nov
4 weeks ago

WallyJ left a reply on Paginating Eloquent Relational Query Results - Eager Loading

After rethinking my efforts, I believe I am going to switch to using JQuery to create an infinite scroll within the div that contains my data, rather than using pagination. No clicking needed, just the scroll wheel.

06 Nov
1 month ago

WallyJ started a new conversation Paginating Eloquent Relational Query Results - Eager Loading

I'm trying to have a section on my contact view that shows contact notes, 4 per page, in a box that goes through pages without refreshing the page. This may require AJAX, but I'm just trying to get the pagination to show at the moment.

Here's my code. Since I'm using the "with" to eager load the "contactnotes", I don't know where to put the pagination function.

Contacts Controller:

//Look up contact chosen by URL
        $contacts = Contact::with(['contactnotes', 'deals.tasks'])->find($id);

        // Check for correct user
        
        if(auth()->user()->id !== $contacts->user_id){
            return redirect('/contacts')->with('error', 'That Is Not Your Contact');
        }

        // Update Last Seen Field for viewed contact
        Contact::where('id', $id)
                    ->update(['contactlastseen' => \Carbon\Carbon::now()]);

        return view('contacts.show', ['contact' => $contacts, 'contactnotes' => $contacts->contactnotes, 'deals' => $contacts->deals]);

View:

<div class="col-md-12">
  <ul class="list-group">
    @foreach($contactnotes->sortByDesc('created_at') as $contactnote)
    <li class="list-group-item">
    {{$contactnote->created_at->diffForHumans()}} - {{$contactnote->contactnotetext}}
    </li>
    @endforeach
  </ul>
</div>

I may ultimately go with a static box with a scroll bar and add infinite scroll capabilities to it, so it doesn't take up much space on the screen and would also not require a page refresh.

Ideas? Thanks!

10 Oct
2 months ago

WallyJ left a reply on ID Does Not Pass From View To Controller

@Cronix , You are correct. I am using a resource controller.

I didn't realize that those controllers could not receive parameters like that.

I guess this is one problem with combining so many learning resources that tutorials get combined into things that sometimes don't work together. I never thought about passing the variable through a hidden field in the form.

Now when I dd($contact), I get the entire record for the correct contact in the DB.

Edited the rest of my code and my form works like a champ now. Thanks!

And thanks to everyone for their feedback. This community is awesome!

WallyJ left a reply on ID Does Not Pass From View To Controller

@jekinney , thanks for the ideas. The form helpers are part of LaravelCollective who continued developing them when Laravel took them out of the framework.

www.laravelcollective.com

I checked the dd and it shows nothing, however, I'm wondering how my route can be wrong when the form sends the information directly to the controller via this line:

{!! Form::open(['route' => ['contactnotes.store', $contact->id]]) !!}

WallyJ left a reply on ID Does Not Pass From View To Controller

@D9705996 , The url the form is on includes something like /contact/5, so the ID is being sent to that page. The contact_id is in the controller, and pulls the $contact->id

@jlrdw , The other fields are passed since "contactnotetext" shows up in the results.

WallyJ started a new conversation ID Does Not Pass From View To Controller

Relationships are set in the model

Form in view:

{!! Form::open(['route' => ['contactnotes.store', $contact->id]]) !!}
                                    {{ csrf_field() }}
                                    <div class="form-group">
                                        {{Form::textarea('contactnotetext', null, array('placeholder' => 'Your note here', 'class' => 'form-control', 'rows' => '3'))}}
                                    </div>
                                    <div class="form-group">
                                        {{Form::submit('Add Note', array('class' => 'btn btn-primary'))}}
                                    </div>
{{Form::close()}}

ContactnotesController:

public function store(Contact $contact, Request $request)
    {
        $contactnote = new Contactnote;
        $contactnote->contact_id = $contact->id;
        $contactnote->contactnotetext = $request->contactnotetext;
        $contactnote->contact()->associate($contact);
        return $contactnote;
    }

I don't understand why the id is not being passed. When I submit the form I get:

{
"contact_id": null,
"contactnotetext": "adsf",
"contact": []
}
08 Oct
2 months ago

WallyJ left a reply on Trying To Get Property Of A Non-object - First()

It was in a foreach loop. I added the optional helper and it worked fine. Thanks!

WallyJ started a new conversation Trying To Get Property Of A Non-object - First()

When I use:

{{$deal->tasks->first()}}

in a view, I get this when rendered:

{"id":1,"created_at":"2018-10-01 00:00:00","updated_at":"2018-10-01 00:00:00","deal_id":11,"tasktext":"Call Client","taskduedate":"2018-04-20","taskcomplete":0}

When I add the following:

{{$deal->tasks->first()->tasktext}}

I get "Trying to get property of a non-object". I can see the field of the record from the previous code. How am I not calling it correctly?

WallyJ left a reply on Limit Results In Eloquent Results Using Relationship Table

@snapey - Looks like that works. I'm going to run some more tests to make sure. I did have something in my view like that. Just didn't click with me. Thanks!

WallyJ left a reply on Limit Results In Eloquent Results Using Relationship Table

@Snapey , does that go in the controller? And if so, where? Thanks!

04 Oct
2 months ago

WallyJ left a reply on Limit Results In Eloquent Results Using Relationship Table

@Cronix , that code returns a total of 3 records across all contacts, not 3 for each contact.

@Snapey , Thanks for the link. I've seen it during my debugging research. There isn't really a clear workaround in that post. Also, it is disheartening to see a bug report like that from 2014 that still doesn't have a clear fix from Laravel or @TaylorOtwell . For a new programmer like me Laravel is supposed to make "plain language" programming easier, and this is a very simple concept. But this is discouraging.

02 Oct
2 months ago

WallyJ left a reply on Limit Results In Eloquent Results Using Relationship Table

The code I placed returns the correct records as written. It returns ALL contacts for the logged in user. It also shows EVERY contact note under every contact. I want it to show ALL contacts, but I don't want it to show ALL the contact notes.

I want the query to limit the number of contact notes for each contact to the latest 3 (not all). So if a logged in user has 10 contacts, each of those contacts has over 100 notes each, that dashboard gets long and unreadable really fast. But if each contact record in the collection only returned the most recent 3 notes, that would be manageable.

Hopefully that makes better sense.

WallyJ started a new conversation Limit Results In Eloquent Results Using Relationship Table

The following code returns "Contacts" with their "Contactnotes", that belong to a given logged in user, in descending order correctly. I am trying to limit the notes per Contact to 3. I tried to add "take(3)" to the $query statement, but it limited the entire result to only 3 contact notes across all contacts. I believe I need to add a @foreach statement to my query, but I'm not sure how.

public function index()
    {
        //Look up contacts associated with the logged in user
        $user_id = auth()->user()->id; 
        $user = User::find($user_id);;
        $contacts = Contact::with(['contactnotes' => function($query) {
            $query->orderBy('updated_at', 'desc');
        }])
        ->with('deals')
        ->orderBy('contact1lastname', 'asc')
        ->where('user_id', '=', $user_id)->get();
        return $contacts;
        return view('dashboard')
        ->with('contacts', $contacts);
    }
27 Sep
2 months ago

WallyJ left a reply on Access Relations Field In View - Property [contactnotetext] Does Not Exist On This Collection Instance

@Snapey , I received the error "Method Illuminate\Database\Eloquent\Collection::with does not exist." on the simplified code you gave me.

WallyJ left a reply on Access Relations Field In View - Property [contactnotetext] Does Not Exist On This Collection Instance

I'm looking to order the contactnotes (not contacts) by the date field (updated_at), and in some views to limit the list to the latest 3 comments.

WallyJ left a reply on Access Relations Field In View - Property [contactnotetext] Does Not Exist On This Collection Instance

Great suggestion. Can I also do an "orderBy" on the contactnotes?

WallyJ started a new conversation Access Relations Field In View - Property [contactnotetext] Does Not Exist On This Collection Instance

I have the following as my controller and view (models have relationships set correctly), but when I try to pull an item from the relations part of a collection, I receive the error "Property [contactnotetext] does not exist on this collection instance"

Model

public function index()
    {
        //Look up contacts associated with the logged in user
        $user_id = auth()->user()->id; 
        $user = User::find($user_id);;

        //Return contacts with contactnotes
        $contacts = Contact::with('contactnotes')->orderBy('contact1lastname', 'asc')->where('user_id', '=', $user_id)->get();
        return view('dashboard')
        ->with('contacts', $contacts);
    }

View

<div>
Notes:
         @foreach($contacts as $contact)
               <div>
                    <p>ContactNote: {{$contact->contactnotes->contactnotetext}}</p>
               </div>
         @endforeach
</div>

If I put this in my controller:

dd($contacts);

I get the see the items under the relations arrow for contactnotes, so I know the data is being sent.

I think I'm just not referencing it in the view correctly.

24 Sep
2 months ago

WallyJ started a new conversation 'node' Is Not Recognized As An Internal Or External Command, Operable Program Or Batch File

I am running a Laravel project on Laragon and am trying out the "new-ish" Puppeteer bridge "PuPHPeteer"...

When I run my code, I receive the following error:

Exit Code: 1(General error) Working directory: C:\laragon\www\Project\public Output: ================ Error Output: ================ 'node' is not recognized as an internal or external command, operable program or batch file.

I double checked and node is installed in Laragon, and I'm using 8.9.1.

Not sure what else I should do. I was running my Puppeteer straight from Javascript and the terminal within Laragon and it was working fine, but now that I'm using PHP, it can't seem to find Node.

16 Aug
3 months ago

WallyJ left a reply on Javascript Within A Blade View, Passing Variables Between PHP And Javascript

Cool. To modify your example a bit, my app would have an existing list of products without prices in the DB (id, productname, price1, price2, price3).

The app queries the DB for a list of products, runs Puppeteer (Javascript) to get prices from 3 different websites (added to Javascript array via push method as part of a loop for each product/3 websites), then adds the prices to the DB with the appropriate products.

WallyJ left a reply on Javascript Within A Blade View, Passing Variables Between PHP And Javascript

@Cronix , Always great and explanatory responses. This is the heart of learning! Thanks for that explanation. I will work on converting the form examples to pull the data from my variables rather than form fields, if I'm understanding you correctly. :)

WallyJ left a reply on Javascript Within A Blade View, Passing Variables Between PHP And Javascript

I appreciate the suggestion. However, most of what I read in tutorials and other posts about PHP, Javascript, and AJAX, is based on form submissions. I don't need to submit a form. I need to run a DB lookup, pass the info to Puppeteer Javascript, which will run, return results, put those in the DB in the correct records, and then notify me that it is finished, (possibly showing me the new records recently added via the datamining process). Maybe I need to look more into examples that don't require form submissions when using AJAX

WallyJ started a new conversation Javascript Within A Blade View, Passing Variables Between PHP And Javascript

So, PHP, server side, Javascript, client side... But when using something like Puppeteer (Javascript) for data mining, I need to pull data from the DB first, send variables from PHP to Javascript (Puppeteer, to mine the correct data), then the results from the mining (Javascript variables) need to be added/appended to the database to particular records, not just edited for screen view (client side).

I want to do this correctly with Laravel using models, routes, views, etc. But the passing back and forth may take multiple views, but maybe not. I also want to keep the Puppeteer Javascript in a separate file and call it when needed in the process.

Just looking for some logical suggestions of file structures and where to place each functional part of my code.

24 May
6 months ago

WallyJ left a reply on Passport Guzzle Response Directs To Login Page

Sorry to tag along, but I have the same issue. If I go to a URL (For a site I am logged into) directly in Chrome, the page shows fine.

But if I use Guzzle and the command:

$client = new \GuzzleHttp\Client();
        $res = $client->request('GET', $url);
        echo $res->getbody();

I receive the login page, as if I'm not logged in, and also in my case, there are no images on the page.

I'm thinking there is a simple fix for this, but I am new to using Guzzle and DOM functions.

20 May
6 months ago

WallyJ left a reply on Count Of Records From DB::select

Thanks Cronix. As you know, sometimes my brain gets stuck wanting to do things one way. This time, I tried the PHP count method before, directly in the SQL query, but couldn't get it to work. Then I realized that I need to be doing things the Laravel way as much as possible (which I am often doing), but couldn't get away from the DB:select to simply declare a variable with a simple count.

This was my solution:

$countofopps = count($homeopps);

and at the end of my return statement, I added:

->with('countofopps', $countofopps);

And simply put this in my view:

{{$countofopps}

Thanks again.

WallyJ left a reply on Count Of Records From DB::select

I added this line to my controller just before the "return view" line and I received this error:

"Call to a member function count() on array"

WallyJ started a new conversation Count Of Records From DB::select

I have the following query in a controller:

$opps = DB::select('SELECT mainfield, field2, etc. FROM table LEFT JOIN ( SELECT otherfield FROM othertable Group By fieldname');
return view ('home')
->with ('opps', $opps)

The query works fine. I just want to get a count of the records returned so that I can put this count at the top of the view.

In the view I currently return the results in a:

@foreach($opps as $opp)

But I want to put the count above the foreach.

I tried:

{{$opp->mainfield->count()}}

But of course it errors out saying it doesn't recognize that variable because it hasn't been called yet.

Just want to put a count of records returned at the top of the view. Thanks.

19 May
6 months ago

WallyJ left a reply on 1366 Incorrect String Value, On CSV Import To MySQL DB

Update 3 - Solution:

I used the mb_convert_encoding function to specify the collation for the fields that were causing errors. (Ended up being 2 fields)

In the controller, I added a line above the field that was problematic, to force UTF8:

$remarks=mb_convert_encoding($remarks, "UTF-8");
$newdata->remarks=$remarks;

WallyJ left a reply on 1366 Incorrect String Value, On CSV Import To MySQL DB

Update 2: So, it turns out that the CSV file I have is not encoded UTF-8.

I opened the file in Notepad, and saved as UTF-8 and it imported like a champ.

I may look at those PHP functions to force that field to be encoded as UTF so I don't have to convert the CSV file every time.

WallyJ left a reply on 1366 Incorrect String Value, On CSV Import To MySQL DB

Update: I took the text directly from the CSV file and inserted it directly into the DB using PHPMyAdmin.

No error, so the DB is able to hold the accented "e".

But I can't figure out what is causing the error.

Any other suggestions? Thanks!

WallyJ left a reply on 1366 Incorrect String Value, On CSV Import To MySQL DB

@rsvb - Thanks for the suggestion, but I believe this is a collation setting issue, not something that needs an additional PHP function to do something to the string.

I understand if I could use the function to test the string possibly. I was just hoping that someone would have experienced this particular error before and knows where the issue is. Still hoping for a solution. Thanks.

18 May
6 months ago

WallyJ left a reply on 1366 Incorrect String Value, On CSV Import To MySQL DB

The error specifically denotes the word with the accented "e", "Incorrect string value: '\xE9cor a...' for column 'Remarks'" and then shows the data with the word showing the accented "e" replaced with that black diamond with the question mark - d�cor

WallyJ left a reply on 1366 Incorrect String Value, On CSV Import To MySQL DB

varchar(800) utf8_unicode_ci

The query returns this field type and collation

WallyJ left a reply on 1366 Incorrect String Value, On CSV Import To MySQL DB

When I upload the CSV, which calls the controller, that's where I receive the error. The value never gets into the column in the DB.

I have tried changing the collation, but it didn't keep the error from happening.

What else can I do?

17 May
6 months ago

WallyJ started a new conversation 1366 Incorrect String Value, On CSV Import To MySQL DB

I receive this error on a field that contains a word with an accented "e" character. I have Googled to find that the issue seems to be in the collation of the data and the tables. I have changed the collation in the db to utf8_unicode_ci as well as utf8_general_ci, and changed my config/database.php to reflect utf8_general_ci, to no effect. I've also read that using "SET NAMES" to UTF8 as part of your query can help, but I'm using a simple $newdata->save() at the end of my field data, so I'm not sure how to do that. Ideas? Thanks.

21 Apr
7 months ago

WallyJ left a reply on Referencing A Variable Within A Controller Is Not Recognized

@Sergiu17 , Follow up. Though this line works beautifully and cleanly, I just noticed that I lost my "orderBy('created_at', 'desc'), and can't figure out how to put it back in to order the contactnotes.

$contacts = Contact::with(['contactnotes'->orderBy('created_at', 'desc'), 'deals.tasks'])->find($id);

WallyJ left a reply on How To Properly Add A Package To My Project

I added the links to the js and the css from the cdnjs and it immediately started working. Thanks.

Unfortunately now I can't get the parameters to work correctly. Will work on that next.

WallyJ left a reply on How To Properly Add A Package To My Project

I appreciate your explanation, and will look into using mix and npm.

So should the developer give a better explanation in the instructions, or is it my job as the developer to understand the ecosystem enough to translate the instructions into what I really ought to do? #trulytryingtolearn

WallyJ left a reply on How To Properly Add A Package To My Project

Appreciate the insight, but in an effort to understand, why would this package be available via composer if composer doesn't really "install" it in a way that it will actually work after installation?

20 Apr
7 months ago

WallyJ started a new conversation How To Properly Add A Package To My Project

I found a cool date picker, and according to the instructions on its page at Packagist, I ran the following command in my terminal:

composer require eternicode/bootstrap-datepicker

I feel like I'm supposed to add something else somewhere, but I don't see it in the instructions on this page, or at the docs linked from that page.

https://packagist.org/packages/eternicode/bootstrap-datepicker

Maybe I'm supposed to know.

19 Apr
7 months ago

WallyJ left a reply on Referencing A Variable Within A Controller Is Not Recognized

Wow... mystery solved...

I had a lingering old field in my contacts table called "contactnotes" when I originally created the table, before I created an entirely different table for "contactnotes". I changed the name of the field, and boom, everything worked as expected.

DD in the controller, then DD in the view, then the view itself.

Thanks guys! #newbmistakes #greatcommunity #thankful

WallyJ left a reply on Referencing A Variable Within A Controller Is Not Recognized

Again, the contact notes were working before I tried to add the tasks. It was at that point I wasn't writing the code correctly to also request the tasks. That's when I was encouraged to use this:

$contacts = Contact::with(['contactnotes', 'deals.tasks')->find($id);

Which was your cleaned up version. :)

So I know the relationships were working and the contactnotes were being found.