jim1506

jim1506

Technical Director at London

Member Since 3 Years Ago

London, UK

Experience Points
7,630
Total
Experience

2,370 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
48
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.

Level 2
7,630 XP
Oct
10
1 week ago
Activity icon

Replied to A Helpers Tip

You are right Sinnbeck. It is only registering classes. You may have a whole series of useful functions. For example in one of my views I start with

@php
  $today_f = ReturnTodayFormatted();
@endphp

and in one of the files in the helper directory I have the appropriate function:

function ReturnTodayFormatted()
    {
    date_default_timezone_set('Europe/London');
    $today = mktime(0, 0, 0, date("m")  , date("d"), date("Y") );
    $today = date('d M, Y',$today );
    return $today;
    };

and likewise I have a slight more complex function

function dateDiff( $endDate, $beginDate)
{
// has to come in as Y-M-D
//gregoriantojd is month day year

$date_parts1=explode($dformat, $beginDate);
$date_parts2=explode($dformat, $endDate);

$start_date=gregoriantojd($date_parts1[1], $date_parts1[2], $date_parts1[0]);
$end_date=gregoriantojd($date_parts2[1], $date_parts2[2], $date_parts2[0]);

$diff = $end_date - $start_date;

return $diff;

};

Using this approach the functions can be used in controllers, views and so on, although both of these examples you can do with Carbon.

One point though is you can of course use App\tablename at the top and so it is available throughout the file, but if you call a facade you must give it an alias so PHP is happy. So I use something like:

use App\Config;
use File as FL;
use Image as IM;

I find this very useful and convenient.

Activity icon

Replied to Should I Start With Laravel 6 Or Master 5.xxx?

I think a lot depends if you use anything from gitHub or Packaglist. Some of them are yet to be updated for 6.

Activity icon

Started a new Conversation A Helpers Tip

On larger projects I tend to have a load of .php files in a directory Helpers. I like to keep them separate so I can easily find something or add.

So I add a HelpersServiceProvider.php in the Providers directory with the following code:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class HelperServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
  /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        foreach (glob(app_path().'/Helpers/*.php') as $filename){
            require_once($filename);
        }
    }
}

It will register all the php files in the directory even if you add or whatever.

Then just add in config/app under Providers

  'App\Providers\HelperServiceProvider',

and it just does it for you.

So you can now call a function in any of your helpers anywhere.

Activity icon

Replied to Count In A Joined Table With DB

Sinnbeck, When I initially tried your query I got

SQLSTATE[42000]: Syntax error or access violation: 1140 In aggregated query without GROUP BY, expression #2 of SELECT list contains nonaggregated column 

so I amended it to

$pr = DB::table('properties')->leftJoin('photos', 'properties.id', '=', 'photos.property_id')->select(DB::raw('count(photos.id) as photos_count'))->addSelect(['properties.id', 'address', 'town', 'postcode', 'units','unitType','examination','priority','completed','quotationRequired'])->groupBy('properties.id', 'address', 'town', 'postcode', 'units','unitType','examination','priority','completed','quotationRequired')->get();

and it worked.

Thanks everyone!

Activity icon

Replied to Count In A Joined Table With DB

use DB;

has always been in the controller.

If I add a \ before the DB I get

syntax error, unexpected '\' (T_NS_SEPARATOR), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'
Activity icon

Replied to Count In A Joined Table With DB

If I run

$pr = DB::table('properties')
    ->leftJoin('photos', 'properties.id', '=', 'photos.property_id')
    ->DB::raw('count(photos.id) as photos_count')
    ->pluck(['properties.id', 'address', 'town', 'postcode', 'units','unitType','examination','priority','completed','quotationRequired']);

I get an error message of

Undefined property: Illuminate\Database\Query\Builder::$DB

so I tried

$pr = DB::table('properties')
    ->leftJoin('photos', 'properties.id', '=', 'photos.property_id')
    ->raw('count(photos.id) as photos_count')
    ->pluck(['properties.id', 'address', 'town', 'postcode', 'units','unitType','examination','priority','completed','quotationRequired']);

and got an error of

Call to undefined method Illuminate\Database\Query\Expression::pluck()
Activity icon

Replied to Getting A Attempt To Assign Property 'admin' Of Non-object When Adding To Users

Thanks Nakov. That was incredibly thick of me (it is 6.35 am here) and of course my attention was on the error and not the error on the line above.

All sorted thanks.

Activity icon

Started a new Conversation Getting A Attempt To Assign Property 'admin' Of Non-object When Adding To Users

I have amended the users table to add an integer field admin. I have a form which includes a checkbox for this:

              <div class="form-group col-xs-12">
                  <div class="checkbox ">
                      <input type="checkbox" name="admin" id="checkbox_372773_0" value="1" data-alias="" checked=""><label for="checkbox_372773_0" class="checkbox-inline">
                      &nbsp;&nbsp;admin </label>
                  </div>

                  <span id="checkbox_372773"></span>
              </div>

and in my controller I have a store method:

public function store(Request $request)
    {
         
         $us = new User;

         $us->name = $request->name;
         $us->email = $request->email;
         $us = Hash::make($request->password);

         if (isset($request->admin))
           { $us->admin = 1;}
         else
           {$us->admin = 0;}

         $us->save();
         session()->flash('success','the user has been added');
         return redirect()->route('users');
    }

if I run this I get the error

Attempt to assign property 'admin' of non-object

so I added

dd($request')

to check the incoming request

request: ParameterBag {#44 ▼
    #parameters: array:6 [▼
      "_token" => "TNaQs6HAwGUbz87PNRJoOeZcurIJgKbKnbEaAbWX"
      "name" => "Jim"
      "email" => "[email protected]"
      "password" => "aPassword"
      "admin" => "1"
      "button_569082" => null
    ]
  }

I have added the field to the fillable on the User.php:

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

but it has made no difference, and of course I have not got to the store part of the controller method.

Activity icon

Replied to Count In A Joined Table With DB

I tried amending the query to:

$pr = DB::table('properties')->leftJoin('photos', 'properties.id', '=', 'photos.property_id')->DB::raw('count(photos.id) as photos_count')->select(['properties.id', 'address', 'town', 'postcode', 'units','unitType','examination','priority','completed','quotationRequired']);

but it didnt' like it giving me

"syntax error, unexpected ':"

so I removed one of the : but got the same thing so I dropped the DB entirely:

$pr = DB::table('properties')->leftJoin('photos', 'properties.id', '=', 'photos.property_id')->raw('count(photos.id) as photos_count')->select(['properties.id', 'address', 'town', 'postcode', 'units','unitType','examination','priority','completed','quotationRequired']);

and got

Call to undefined method Illuminate\Database\Query\Expression::select()

Activity icon

Started a new Conversation Count In A Joined Table With DB

I have some code to get data for a datatable

$pr = DB::table('properties') ->leftJoin('photos', 'properties.id', '=', 'photos.property_id') ->select(['properties.id', 'address', 'town', 'postcode', 'units','unitType','examination','priority','completed','quotationRequired']);

This works fine but I would like to add the count of photos in my select statement.

Help appreciated!

Dec
03
10 months ago
Activity icon

Started a new Conversation If You Have A Lot Of Php Method Files That You Have Built Up Over The Years...

I put these into a directory app\Helpers and then in the Providers directory make a new provider HelperServiceProvider. The code for this just reiterates though a directory of php files:

 <?php

namespace App\Providers;

 use Illuminate\Support\ServiceProvider;

 class HelperServiceProvider extends ServiceProvider
{
/**
 * Bootstrap the application services.
 *
 * @return void
 */
public function boot()
{
    //
}

/**
 * Register the application services.
 *
 * @return void
 */
public function register()
{
    foreach (glob(app_path().'/Helpers/*.php') as $filename){
        require_once($filename);
        }
    }
} 

finally add it to config/app under providers:

'App\Providers\HelperServiceProvider',

and all your methods are available

Activity icon

Started a new Conversation A Tip When Using JQuery UI Laravel 5.7

I set up a new project and then added jQueryUi the main home page as I wanted the tabs:

<link href="{{ asset('jqueryui/jquery-ui.min.css') }}" rel="stylesheet">
<link href="{{ asset('jqueryui/jquery-ui.structure.min.css') }}" rel="stylesheet">
<link href="{{ asset('jqueryui/jquery-ui.theme.min.css') }}" rel="stylesheet">

It didn't work although it has worked perfectly on other projects and I was receiving a jQuery error..

I found that if I took out

<script src="{{ asset('js/app.js') }}" defer></script>

it worked, but then things in the menu did not work so that was not a great start and then I found if you delete defer from the app.js call all is fine:

<script src="{{ asset('js/app.js') }}"></script>
Dec
01
10 months ago
Activity icon

Started a new Conversation Backpack For Laravel - Several Different Image Uploads In CRUD Form

I have a countries table with 3 fields to store image names:

  1. flag
  2. capitalPhoto
  3. banner
  4. map

In my CRUD form I have the 4 upload fields defined and initially has two mutators for flag and capitalPhoto with no problems by defining two functions:

public function setflagAttribute($value) {...}
public function setcapitalPhotoAttribute($value) {...}

when I try to add the last 2 it fails as it tries to store the data in the database as opposed to uploading it.

I have tried to see if there is part of the image field type which enables me to say which mutator to use.

Anyone else come across this and solved it?

Thanks!

Oct
11
1 year ago
Activity icon

Replied to Datatables From A Raw Query

Can I recommend using Laratables.

https://github.com/freshbitsweb/laratables

It is very easy and uses Eloquent models (including relationships).

Oct
07
1 year ago
Activity icon

Replied to Php Artisan Cache:clear (have The Appropriate Permissions.)

I had this problem also with Windows10 but adding the data fixed worked

Aug
07
1 year ago
Activity icon

Replied to Problem With A Link To Download A File

I tried this but I am still getting "Firefox can’t find the file at http://localhost:8000/stconnection/St Helena_Connection_No_18.pdf."

It is definitely there.

Activity icon

Started a new Conversation Problem With A Link To Download A File

I have some pdf's stored in a subdirectory of public named stconnection. They are definitely there.

I have a link to a method (Laravel 5.5) in my view:

view this edition

The database has the correct information.

In the routes.php I have:

Route::get('showSHC/{fl}','[email protected]')->name('showSHC');

In my DownloadsController I have the following function:

public function showSHC($fl) { $type = "application/pdf"; dd(public_path() ); $shc = public_path()."\stconnection\".$fl; //dd($shc); return response()->download($shc); }

However I always get a file not found error. If uncomment the dd($shc) it is perfectly correct.

Help please!!

Jul
08
1 year ago
Jul
01
1 year ago
Activity icon

Replied to Using Named Route With Parameters In A Javascript Call

I have changed to var url = '/noBodyDetail/' + id; but I am getting a 404 when I examine with developer Tools, although the named route is definitely there.

Activity icon

Replied to Using Named Route With Parameters In A Javascript Call

Composer gives an error saying 5.6 is needed and I cannot find an alternative installation on the github site

Activity icon

Replied to Using Named Route With Parameters In A Javascript Call

Ziggy is for 5.6, but because of my client I am forced to use 5.5

Activity icon

Started a new Conversation Using Named Route With Parameters In A Javascript Call

I have a route in my web.php file:

Route::get('noBodyDetail/{id}','[email protected]')->name('noBodyDetail');

and in a datatables I am trying to establish a link using a javascript call:

<a href="#" onclick="showDetail({{ $im->id }})">@fa('eye')</a>

All OK so far.

My problem is calling the named route in a javascript function.

I have tried

function showDetail(id)

{ var url = "{{ route('noBodyDetail') }}/" + id;

$( "#detail" ).empty();

$( "#detail" ).load( url ); }

But I am getting a missing parameter error

Missing required parameters for [Route: noBodyDetail] [URI: admin/noBodyDetail/{id}].

Can someone point out to me how to call a named route and passing a parameter in a javascript function?

Thanks!

Apr
30
1 year ago
Activity icon

Replied to Server Returning 500 Error In One Setting But Not Another With Autocomplete

I managed to sort it out. If you set the value in

````

everything fails.

The answer is very simple set it after the ui is called.

So my form includes:

<div class="ui-widget">
          <label for="author" style="width:10%">author:</label>
           <input id="author" name="author" style="width:50%">
</div>

and I invoke the ui with

$(function()
  {
     $( "#author" ).autocomplete({
      source: "{{ route('autocompleteAuthors') }}",
      minLength: 3,
      select: function(event, ui) {
        $('#q').val('ui.item.value');
      }
    });
  });

and then I add the initial value:

$( "#author" ).val("{{ $author[0]['name'] }}");

Works perfectly

Mar
20
1 year ago
Activity icon

Replied to Server Returning 500 Error In One Setting But Not Another With Autocomplete

Thanks for the replies.

Biishmar the two autocompletes are on difference pages. The first quoted is from a simple test page, the second from a different edit page.

Using Chrome's developer tools I can see the request is OK:

Request URL:http://localhost:8000/admin/editQuote/autocompleteAuthors?term=Bar
Request Method:GET
Status Code:500 Internal Server Error
Remote Address:127.0.0.1:8000
Referrer Policy:no-referrer-when-downgrade

The Response Headers are:

Cache-Control:no-cache, private
Connection:close
Content-Type:application/json
Date:Tue, 20 Mar 2018 10:14:21 +0000
Date:Tue, 20 Mar 2018 10:14:21 GMT
Host:localhost:8000
Set-Cookie:XSRF-TOKEN=eyJpdiI6ImV3RW5nRlFpZVJSaWhXY2t5WnlkYVE9PSIsInZhbHVlIjoiTGFVcWg0REd0TTdEWjVpNWk5YU1cL0FYalM2OGc5SkFNZjBlSW81VjlnNXRrbHIreWc1dDlnQkpDbU94amxBMlhPdnc5TDN5M1BtY3RBVUFFcXNvVml3PT0iLCJtYWMiOiIyODBhOWU5M2MxNGFmYWJjYTBmYTZkMGI4NTIwZmJlNjRlMmRiNzRmMDlkMjQzZDJhYmVmMWRmMTY1NGE4NDI2In0%3D; expires=Tue, 20-Mar-2018 12:14:21 GMT; Max-Age=7200; path=/
Set-Cookie:laravel_session=eyJpdiI6IkI5K2NsUzJScjI2T3FuUkNvZmQxbGc9PSIsInZhbHVlIjoiYmJRd3FJbXNkMjQ3UzY3c3dnR2FJWGZzTGM5VktCeGNhTjExTnNqdXNzcjB1Z1VYS3BjNStcLzYyK0JQbUdaMU1MUzVtVGFram5ueWFYMlhHNHFEWUhRPT0iLCJtYWMiOiI0NzQ3NGNlOTQ2NTQwYWNmYTI2YmI2OTAyZWY0MWQyYjI1YTJhZWFhMjI5YWVkNDNjNGY4NmUzMGEwZWFmOTdjIn0%3D; expires=Tue, 20-Mar-2018 12:14:21 GMT; Max-Age=7200; path=/; HttpOnly
X-Powered-By:PHP/7.1.1
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
Connection:keep-alive
Cookie:laravel_cookie_consent=1; cookieconsent_dismissed=yes; _ga=GA1.1.800086270.1516873566; remember_web_59ba36addc2b2f9401580f014c7f58ea4e30989d=eyJpdiI6ImhsQTlkbDJXZ2NHWWl3MFQ3a3FzZ2c9PSIsInZhbHVlIjoiV2d3Z2Qya2JmZ1UxQ0pweXlscVEwaU5PMzRHR2ZcL1huUkxYVXhJckNHOEdobnhjajBDVXNrXC82M2VRZjkzTGdTRm1qakZaMXJUSlpoR1NESUkzbWd2d0VnRnBOSTFYamEyWDB3Tng2K01CMXkyaUNoMGh6bkRHbEpkc3B2VXR1S3FQdmZ4RFJET3JrZ0ZHblNjUVhnOGh1RnVVRHNUXC9nQTk0WnhUTmNMRE5QUmkyalR0cUNuY3JTYnNGTmkzSFwvYiIsIm1hYyI6IjZkNzhmNWQ3MmQ1ZjVkNzYwMDQwMjNhYzU0MmI4ZjhjNTg2MzFkNWNlYTllNjJlYmI1YzUyNDM4YTU0ZDNkNTUifQ%3D%3D; XSRF-TOKEN=eyJpdiI6IkFJXC9xNU5FbUt5aTZTczI1ekVlYkdBPT0iLCJ2YWx1ZSI6IlVBclh4czZXNmU1YzJKZlphdytvY0tPVmpOU3ZySjVzT292MXNNUzRhU0NBSWhUMlBnVm1YblZJcENzYlJJKzFVdXJlMUlHbkNGWGRFaWNKT2k5Y293PT0iLCJtYWMiOiI3ZjliYWUzZTYwNjE4OTJhOWNjM2FlYTI1NzBmMTFhZGM1MGJhNmFlZWIzZTZmODFmNDJjYzYxMjY5N2U2MTQ5In0%3D; laravel_session=eyJpdiI6IlFPMU1xNEJWQ1U3b2F2MHZZZHlOdUE9PSIsInZhbHVlIjoiTmdnQURNNGVsenRjeGNvVDVuRjBFSFVXMks5dlR2NlwvNFwvRHNmN2VKQlJ0ZHAyV0VUb284ZllvaVhvd1BTT1lTWkU3N2Q5S3VqZktqRkt6SHNqbmFmZz09IiwibWFjIjoiOWY4OGIzN2ZhMzViMzk4NTA2N2UzNzQzOGRlNGE4MGZkY2U2ODJjMjM5NDE1YjQyYWNiNTI3MGVjZjVmN2U5MiJ9
Host:localhost:8000
Referer:http://localhost:8000/admin/editQuote/86797
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36
X-Requested-With:XMLHttpRequest

and the query string is

term:Bar

It seems an inability on the edit form to handle the json response. I have even tried leaving out the value of the of the name in the field.

Mar
19
1 year ago
Activity icon

Started a new Conversation Trying To Get Info Via Guzzle But Receiving A 500 Error

I have installed Guzzle via composer and have reference it in a controller

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;

I am trying to return data from a source with a function in the controller:

$client = new Client(); //GuzzleHttp\Client
          $result = $client->get('http://webservices.capnetwork.co.uk/CAPVehicles_Webservice/capvehicles.asmx/GetCAPMan',
               ['query' => [
                  'Subscriber_ID' => 'XXXXXX',
                  'Password' => 'XXXXX',
                  'Database' => 'CAR',
                  'JustCurrentManufacturers' => 'TRUE']
              ]);
  dd($result);

but I am receiving:

Server error: `GET http://webservices.capnetwork.co.uk/CAPVehicles_Webservice/capvehicles.asmx/GetCAPMan?Subscriber_ID=XXXX&Password=XXXXX&Database=CAR&JustCurrentManufacturers=TRUE` resulted in a `500 Internal Server Error` response:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml (truncated...)

Obviously I have the correct ID and password.

Activity icon

Started a new Conversation Server Returning 500 Error In One Setting But Not Another With Autocomplete

I have a simple form to get an autocomplete of an author's name from a table of several thousand.

In my simple form I have:

<form>
     <div class="ui-widget">
        <label for="authors">authors: </label>
        <input id="authors" value="">
     </div>
</form>

The javascript is:

<script>
 $(function()
  {
  $( "#authors" ).autocomplete({
  source: "autocompleteAuthors",
  minLength: 3,
  select: function(event, ui) {
    $('#q').val(ui.item.value);
  }
 });
});
</script>

I have a route pointing to a controller:

Route::get('autocompleteAuthors','[email protected]')->name('autocompleteAuthors');

and a function in the controller:

public function authors()
  {
    $term = Input::get('term');
    $results = array();

    $queries = DB::table('author')
        ->where('name', 'LIKE', '%'.$term.'%')
        ->take(5)->get();

    foreach ($queries as $query)
    {
        $results[] = [ 'id' => $query->id, 'value' => $query->name];
    }
  return Response::json($results);
  }

This works fine.

In a form to edit a quote (part of the edit could be the author) I have the following:

<div class="ui-widget">
     <label for="author" style="width:10%">author:</label>
     <input id="author" name="author" value="{{ $author[0]->name }}" style="width:50%">
</div>

and the javascript is:

<script>
   $(function()
   {
    $( "#author" ).autocomplete({
    source: "autocompleteAuthors",
    minLength: 3,
    select: function(event, ui) {
    $('#q').val(ui.item.value);
   }
 });
});
</script>

So they are both sending "term" to the same route yet in the second case I get a 500 error.

Can't see any reason for this!

Mar
05
1 year ago
Activity icon

Replied to Type Ahead Not Firing

Well I have tried everything and wasted 1 day so I have reverted to jqueryui. Make the list:

use \App\Countries;
     $cts = Countries::orderBy('country')->get();
     $list = "";
     foreach ($cts as $item)
      {
        $list = $list.'"'.$item->country."\",";
      }

and then fire it up:

<script>
  $( function() {
      var availableTags = [
        <?php echo $list; ?>
      ];
      $( "#countries" ).autocomplete({
        minLength: 3,
        source: availableTags
      });
    } );
    </script>

Works fine.

Mar
04
1 year ago
Activity icon

Replied to Type Ahead Not Firing

No. Nothing.

Activity icon

Started a new Conversation Type Ahead Not Firing

I am attempting to get a simple typeahead working. I have a form with the followiong:

                      <div class="form-group">
                         <input class="typeahead form-control" style="margin:0px auto;width:300px;" type="text">
                      </div>
                  </form>

In my form I am loading the appropriate file (jQuery is loaded in the main layout):

<script src="{{ asset('js/typeahead.bundle.js') }}"></script>
  <script>
  var path = "{{ route('autocomplete') }}";
      $('input.typeahead').typeahead({
          source:  function (query, process) {
          return $.get(path, { query: query }, function (data) {
                  return process(data);
              });
          }
      });
  </script>

i have set up a route:

Route::get('autocomplete','[email protected]')->name('autocomplete');

and the Test controller has the following:

public function autocomplete(Request $request)
      {
          $data = Countries::select("country as name")->where("country","LIKE","%{$request->input('query')}%")->get();
          return response()->json($data);
      }

I have Countries in the uses.

Nothing seems to happen!

Mar
31
2 years ago
Activity icon

Replied to Calling A Route From Javascript

I have found datatables with 5.4 very unreliable

Activity icon

Started a new Conversation Calling A Route From Javascript

I have a datatable and I have added an icon for edit to the table. I have an onlick which calls editItem and passes the key in.

function editItem(id)
    {}

What I want to do is the call [email protected] and pass the id parameter to it.

I can of course get the URL of the item with something like:

 editRoute = "{{ route('editUser')}}"; 
        alert(editRoute);

and pass the id as a part of the URL but I am wondering if there is a more eloquent way of doing this?

Mar
19
2 years ago
Activity icon

Started a new Conversation Call A PHP Page (not Blade) From A Controller

I have been battling Datatables with 5.4 without any success and have decided that I will have to walk another route as I cannot give it more time.

I have therefore a page in the public area in a subdirectory called ajax, datatables_users.php.

This page generates a datatable using server side processing fine (which I could never get to work in 5.4) so I just want to call it from a controller.

I have tried

return view("asset('ajax\datatables_user.php')") ;

but I am getting a

Class Barstone\Http\Controllers\../ajax/datatables_user.php does not exist

How can a call a "raw" php page from a controller?

Thanks

Mar
17
2 years ago
Activity icon

Replied to Datatables As A Service With 5.4

If you try it with 5.4 it does not work

Mar
12
2 years ago
Activity icon

Replied to Datatables As A Service With 5.4

No its no there:

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

Auth::routes();

Route::get('/home', '[email protected]');

Route::resource('test', 'UsersController');

Activity icon

Replied to Datatables As A Service With 5.4

I have done that but for some reason I am still getting:

ReflectionException in RouteSignatureParameters.php line 25: Class Barstone\Http\Controllers\UsersDataTable does not exist
Activity icon

Replied to Datatables As A Service With 5.4

So the UsersController is now

<?php
namespace Barstone\Http\Controllers;
use Barstone\DataTables\DataTablesBase;
use Illuminate\Http\Request;
use Barstone\User;

class UsersController extends Controller
{
    protected $table = "users";

    public function index(UsersDataTable $dataTable)
    {
       
        $query = User::select('id','name','email','active');
        $dataTable = Datatables::of($query);
        $columns = ['id','name','email'.'active'];
        $base = new DataTableBase($query, $dataTable, $columns);
         return $base->render(null);
     }  

    public function fetchUsers() {
        return Datatables::collection(User::get())->make(true);
    }
}

The DataTablesBase starts with

namespace Barstone\DataTables;

use Illuminate\Contracts\View\Factory;
use Illuminate\Database\Query\Builder;
use Yajra\Datatables\Datatables;
use Yajra\Datatables\Engines\BaseEngine;
use Yajra\Datatables\Services\DataTable;

but I am still getting

Class Barstone\Http\Controllers\UsersDataTable does not exist

which I cannot see referenced anywhere

Activity icon

Replied to Datatables As A Service With 5.4

I've triple checked and the UsersDataTable is headed by

namespace Barstone\Http\Controllers;
use Barstone\DataTables\UsersDataTable;
use Illuminate\Http\Request;
use Barstone\User;

which is correct

Activity icon

Replied to Datatables As A Service With 5.4

Sorry where is DataTablesBase.php?

Activity icon

Replied to Datatables As A Service With 5.4

My namespace is Barstone and I am now getting:

ReflectionException in RouteSignatureParameters.php line 25: Class Barstone\DataTables\UsersDataTable does not exist

The file does exist

Activity icon

Replied to Datatables As A Service With 5.4

The view is

@extends('layouts.  app')

@section('content')
{!! $dataTable->table() !!}
@endsection

@push('scripts')
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.0.3/css/buttons.dataTables.min.css">
<script src="https://cdn.datatables.net/buttons/1.0.3/js/dataTables.buttons.min.js"></script>
<scr``ipt src="/vendor/datatables/buttons.server-side.js"></script>
{!! $dataTable->scripts() !!}
@endpush

The Controller is

public function index(UsersDataTable $dataTable)
    {
       
       return $dataTable->render('users.users');
     }  

The model is exactly as the example on

https://datatables.yajrabox.com/service

Activity icon

Started a new Conversation Datatables As A Service With 5.4

I have battled with this for some time and am getting nowhere. I have followed the instructions on https://datatables.yajrabox.com/service (remembering the update page) but nothing works.

Has anyone a good tutorial for datatables as a service with 5.4?

Feb
09
2 years ago
Activity icon

Replied to Datatables From A Raw Query

Thanks. This is a great addition

Jan
11
2 years ago
Activity icon

Replied to Datatables Raw Query Giving SQL Error

I changed the route to:

Route::get('/partdetails/serverSide',[
    'as' => 'partdetails.serverSide',
   'uses' => function(){
            $parts =  App\PartDetail::selectRaw("partdetails.ID AS ID, partdetails.PartNo AS PartNo, partdetails.Description as Description, manufacturer.Manufacturer AS Manufacturer")->join('manufacturer', 'entry', '=', 'partdetails.manufacturer')->orderBy('partdetails.ID')->limit(30)->get();
           // dd($parts);
          return Datatables::of($parts)->make();
    }
]);

and it is perfect. Thanks so much!

Jan
10
2 years ago
Activity icon

Replied to Datatables Raw Query Giving SQL Error

DD now only gives me (just first items):

Collection {#249 ▼
  #items: array:21193 [▼
    0 => {#250 …5}
    1 => {#252 …5}
    2 => {#253 …5}
    3 => {#254 …5}
    4 => {#255 …5}
    5 => {#256 …5}
    6 => {#257 …5}
    7 => {#258 …5}
    8 => {#259 …5}
    9 => {#260 …5}
Activity icon

Replied to Datatables Raw Query Giving SQL Error

I changed the route to :

Route::get('/partdetails/serverSide',[
    'as' => 'partdetails.serverSide',
   'uses' => function(){
        $sql = 'SELECT partdetails.ID, partdetails.PartNo, partdetails.Description, manufacturer.Manufacturer, partdetails.accountcode FROM partdetails  INNER JOIN manufacturer  ON partdetails.Manufacturer = manufacturer.entry ORDER BY partdetails.PartNo ASC';

            $parts= DB::table(DB::raw("($sql) AS TheParts"))->get();   
            
            return view ('stock.parts', ['parts'=>$parts]);
    }
]);
Activity icon

Replied to Datatables Raw Query Giving SQL Error

I am now getting

DataTables warning: table id=thetable - Invalid JSON response
Activity icon

Started a new Conversation Datatables Raw Query Giving SQL Error

I have an AJAX route for a datatables view and an SQL that I wish to use of:

SELECT partdetails.ID, partdetails.PartNo, partdetails.Description, manufacturer.Manufacturer, partdetails.accountcode FROM partdetails  INNER JOIN manufacturer  ON partdetails.Manufacturer = manufacturer.entry ORDER BY partdetails.PartNo ASC

I can run this query in Navicat with no problems at all.

I therefore have a route:

Route::get('/partdetails/serverSide',[
    'as' => 'partdetails.serverSide',
   'uses' => function(){
        $sql = 'SELECT partdetails.ID, partdetails.PartNo, partdetails.Description, manufacturer.Manufacturer, partdetails.accountcode FROM partdetails  INNER JOIN manufacturer  ON partdetails.Manufacturer = manufacturer.entry ORDER BY partdetails.PartNo ASC';
            $parts= DB::table(DB::raw("($sql)"))->get();            
            return view ('stock.parts', ['parts'=>$parts]);
    }
]);

When I run this I get

SQLSTATE[42000]: Syntax error or access violation: 1248 Every derived table must have its own alias (SQL: select * from (SELECT partdetails.ID, partdetails.PartNo, partdetails.Description, manufacturer.Manufacturer, partdetails.accountcode FROM partdetails INNER JOIN manufacturer ON partdetails.Manufacturer = manufacturer.entry ORDER BY partdetails.PartNo ASC))

I cannot understand this and need help please!

Thanks

Jan
08
2 years ago
Activity icon

Started a new Conversation Datatables From A Raw Query

I have a datatable in a view that is server processing as the table has several thousand records. I have attempted to use eloquent to get the data but by faw the easiest is a raw SQL.

My view is

 <table id="thetable" class="table table-striped table-bordered" width="90%" align="center" cellspacing="5px" cellpadding="10px" >
        <thead>
        <th>ID</th>
        <th>PartNo</th>
        <th>Description</th>
        <th>ManufacturerName</th>       
        <th>accountcode</th>
        
        </thead>
    </table>
</div>
<script>
     $('#thetable').DataTable({
                dom: 'lBfrtip',
                "iDisplayLength": 30,
                "lengthMenu": [ 10, 25,30, 50, 75, 100,200 ],
                buttons: [
                    'copy',  'print',
                    {extend: 'excel',
                        filename: 'PartDetails', footer:true},
                    {extend: 'pdf',
                        filename:  'PartDetails'},
                    {extend:'csvHtml5',
                        filename: 'PartDetails'},
                    {extend: 'collection',
                        text: 'columns',
                        buttons:['columnsVisibility'] }
                ],
                processing: true,
                serverSide: true,
                ajax: 
                    {url: ' {{ route('partdetails.serverSide') }}',
                    type: 'GET' }
                }) ;
 </script>

My data is supplied by

Route::get('/partdetails/serverSide',[
    'as' => 'partdetails.serverSide',
   'uses' => function(){
        $parts = DB::select('SELECT partdetails.ID, partdetails.PartNo, partdetails.Description, manufacturer.Manufacturer AS ManufacturerName, partdetails.accountcode FROM partdetails INNER JOIN manufacturer ON partdetails.Manufacturer = manufacturer.entry ORDER BY partdetails.PartNo ASC');
        return Datatables::of($parts)->make();
    }

If I dd the $parts it is all correct and myh columns in datatables are perfectly correct but I get an ajax error which is

DataTables warning: table id=thetable - Ajax error. For more information about this error, please see http://datatables.net/tn/7

The table and the names are perfectly correct. Is this something because I am using DB select?

Thanks...