jim1506

jim1506

Technical Director at London

London, UK

Hire Me

Member Since 2 Years Ago

Experience Points 6,600
Experience
Level
Lessons Completed 40
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.

03 Dec
1 week ago

jim1506 started a new conversation If You Have A Lot Of Php Method Files That You Have Built Up With Methods 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 you methods are available

jim1506 started a new conversation A Tip When Using JQuery UI

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>
01 Dec
1 week ago

jim1506 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!

11 Oct
2 months ago

jim1506 left a reply on 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).

07 Oct
2 months ago

jim1506 left a reply on Php Artisan Cache:clear (have The Appropriate Permissions.)

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

07 Aug
4 months ago

jim1506 left a reply on 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.

jim1506 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!!

08 Jul
5 months ago
01 Jul
5 months ago

jim1506 left a reply on 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.

jim1506 left a reply on 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

jim1506 left a reply on 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

jim1506 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

 {

   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!
30 Apr
7 months ago

jim1506 left a reply on Server Returning 500 Error In One Setting But Not Another With Autocomplete

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

<input id="author" name="author" value="{{ $author[0]->name }}" style="width:50%">

everything fails.

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

So my form includes:

` author:

`

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

20 Mar
8 months ago

jim1506 left a reply on 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.

19 Mar
8 months ago

jim1506 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.

jim1506 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:

authors:

The javascript is:

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

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:

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

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!

05 Mar
9 months ago

jim1506 left a reply on 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.

04 Mar
9 months ago

jim1506 left a reply on Type Ahead Not Firing

No. Nothing.

jim1506 started a new conversation Typehead 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!

31 Mar
1 year ago

jim1506 left a reply on Calling A Route From Javascript

I have found datatables with 5.4 very unreliable

jim1506 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.

{}```

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?
19 Mar
1 year ago

jim1506 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

17 Mar
1 year ago

jim1506 left a reply on Datatables As A Service With 5.4

If you try it with 5.4 it does not work

12 Mar
1 year ago

jim1506 left a reply on 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');

jim1506 left a reply on 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

jim1506 left a reply on 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

jim1506 left a reply on 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

jim1506 left a reply on Datatables As A Service With 5.4

Sorry where is DataTablesBase.php?

jim1506 left a reply on 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

jim1506 left a reply on 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

jim1506 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?

09 Feb
1 year ago

jim1506 left a reply on Datatables From A Raw Query

Thanks. This is a great addition

11 Jan
1 year ago

jim1506 left a reply on 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!

10 Jan
1 year ago

jim1506 left a reply on 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}

jim1506 left a reply on 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]);
    }
]);

jim1506 left a reply on Datatables Raw Query Giving SQL Error

I am now getting

DataTables warning: table id=thetable - Invalid JSON response

jim1506 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

08 Jan
1 year ago

jim1506 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...

06 Jan
1 year ago

jim1506 left a reply on Show Results Of A Relationship In A List

Sorry somehow I pressed best answer instead of edit. I forgot the attributes of the main table:

Collection {#255 ▼
  #items: array:20 [▼
    0 => PartDetail {#270 ▼
      #table: "partdetails"
      #primaryKey: "ID"
      +timestamps: false
      #connection: "common"
      #keyType: "int"
      #perPage: 15
      +incrementing: true
      #attributes: array:21 [▼
        "ID" => 92253
        "PartNo" => null
        "Description" => "ShoreTel Refurnished 115"
        "ListPrice" => null
        "SterlingListPrice" => null
        "Manufacturer" => 70
        "BulkName" => null
        "BulkItem" => 0
        "tocheck" => 0
        "accept" => 1
        "dateditem" => 0
        "softitem" => 0
        "mobilecomms" => 0
        "support" => 0
        "consumables" => 0
        "fixedasset" => 0
        "softwaresupport" => 0
        "security" => 0
        "wireless" => 0
        "partgroup" => 0
        "accountcode" => null
      ]
      #original: array:21 [▶]
      #relations: array:1 [▼
        "Manufacturer" => Manufacturer {#248 ▼
          #table: "manufacturer"
          #primaryKey: "entry"
          +timestamps: false
          #connection: "common"
          #keyType: "int"
          #perPage: 15
          +incrementing: true
          #attributes: array:2 [▼
            "entry" => 70
            "Manufacturer" => "Shoretel"
          ]
          #original: array:2 [▶]
          #relations: []
          #hidden: []
          #visible: []
          #appends: []
          #fillable: []
          #guarded: array:1 [▶]
          #dates: []
          #dateFormat: null
          #casts: []
          #touches: []
          #observables: []
          #with: []
          +exists: true
          +wasRecentlyCreated: false
        }
      ]
      #hidden: []
      #visible: []
      #appends: []
      #fillable: []
      #guarded: array:1 [▶]
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      +exists: true
      +wasRecentlyCreated: false
    }

jim1506 left a reply on Show Results Of A Relationship In A List

Ok here is the first record. The manufacturer is correct:

Collection {#255 ▼
  #items: array:20 [▼
    0 => PartDetail {#270 ▼
      #table: "partdetails"
      #primaryKey: "ID"
      +timestamps: false
      #connection: "common"
      #keyType: "int"
      #perPage: 15
      +incrementing: true
      #attributes: array:21 [▶]
      #original: array:21 [▶]
      #relations: array:1 [▼
        "Manufacturer" => Manufacturer {#248 ▼
          #table: "manufacturer"
          #primaryKey: "entry"
          +timestamps: false
          #connection: "common"
          #keyType: "int"
          #perPage: 15
          +incrementing: true
          #attributes: array:2 [▶]
          #original: array:2 [▶]
          #relations: []
          #hidden: []
          #visible: []
          #appends: []
          #fillable: []
          #guarded: array:1 [▶]
          #dates: []
          #dateFormat: null
          #casts: []
          #touches: []
          #observables: []
          #with: []
          +exists: true
          +wasRecentlyCreated: false
        }
      ]
      #hidden: []
      #visible: []
      #appends: []
      #fillable: []
      #guarded: array:1 [▶]
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      +exists: true
      +wasRecentlyCreated: false
    }

jim1506 left a reply on Show Results Of A Relationship In A List

That does not show the manufacturer at all.

dd is showing it correctly but I thinkk the problem is in

@foreach($parts as $items)
    {{ $items['PartNo'] }}, {{ $items['Description']}},  {{ $items->Manufacturer->Manufacturer }}<br/>
@endforeach 

jim1506 started a new conversation Show Results Of A Relationship In A List

I am using legacy tables and have a model for PartDetail:

class PartDetail extends Model
{
    protected $table = 'partdetails';
    protected $primaryKey = 'ID';
    public $timestamps = false;
    protected $connection = 'common';

    public function Manufacturer()
        {
             return $this->hasOne('\App\Manufacturer','entry','Manufacturer');
        }
}

My Manufacturersmodel is

class Manufacturer extends Model
{
    protected $table = 'manufacturer';
    protected $primaryKey = 'entry';
    public $timestamps = false;
    protected $connection = 'common';

    public function Parts()
        {

             return $this->hasMany('\App\PartDetail','Manufacturer','entry');
        }
}

and so I have a route:


Route::get('/partdetails', function(){
    $parts = App\PartDetail::with('Manufacturer')->orderBy('PartNo')->limit(20)->get();
    return view ('stock.parts', ['parts'=>$parts]);
});

If I dd($parts) all is correct but if I try to list the manufacturer is ignored:

<?php //dd($parts); ?>

@foreach($parts as $items)
    {{ $items['PartNo'] }}, {{ $items['Description']}},  {{ $items->Manufacturer->Manufacturer }}<br/>
@endforeach

Any ideas what I am during wrong please?

29 Dec
1 year ago

jim1506 left a reply on Datatables Returning An Error

sorted it - typo in script giving the error that actually was nnot related!

columnDefs: [
                    {'orderable':false, "targets": 3    },
                    {"targets": [3], 
                        "render": function ( data, type, full, meta ) {
                            
                            if(data == 1) 
                                {return '<span style="color: green"><i class="fa fa-check"> </i></span>'; }
                            else
                                {return '<span style="color: red"><i class="fa fa-times"> </i></span>'; }
                            }
                            
                    },
                    {"targets": [4], 
                        "render": function ( data, type, full, meta ) {
                            
                            if(data == 1) 
                                {return '<span style="color: green"><i class="fa fa-check"> </i></span>'; }
                            else
                                {return '<span style="color: red"><i class="fa fa-times"> </i></span>'; }
                            }
                            
                    }
                    
                ]
28 Dec
1 year ago

jim1506 started a new conversation Datatables Returning An Error

I have a view which is populated by the users table which has 2 additional fields to the standard - active (which will be a 1 or a 0) and admin (which also will be a 1 or a 0).

Here is the view and datatables script:

<div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title">Panel title</h3>
  </div>
  <div class="panel-body">
    <table id="thetable" class="datatable" width="90%" align="center" cellspacing="5px" cellpadding="10px" >
        <thead>
          <tr>          
            <th>name</th>
            <th>email</th>
            <th>created</th>
            <th>active</th>
            <th>admin</th>
          </tr>
          <tr>
          <td colspan="5"><hr/></td>
          </tr>
        </thead>
        <tbody>
            @foreach ($users as $item)
                <tr>                    
                    <td>{{$item->name}}</td>
                    <td>{{$item->email}}</td>
                    <td><?php echo date_format($item->created_at,'jS M, Y'); ?></td>
                    <td align="center">{{$item->active}}</td>
                    <td align="center">{{$item->admin}}</td>
                </tr>
            @endforeach
        </tbody>
    </table>
  </div>
</div>

<script>
     $('#thetable').DataTable({
        dom: 'lBfrtip',
                "iDisplayLength": 30,
                "lengthMenu": [ 10, 25,30, 50, 75, 100,200 ],
                buttons: [
                    'copy',  'print',
                    {extend: 'excel',
                        filename: 'users', footer:true},
                    {extend: 'pdf',
                        filename:  'users'},
                    {extend:'csvHtml5',
                        filename: 'users'},
                    {extend: 'collection',
                        text: 'columns',
                        buttons:['columnsVisibility'] }
                ],
                columnDefs: [
                    {'orderable':false, "targets": 3    },
                    {"targets": [3], 
                        "render": function ( data, type, full, meta ) {
                            if(data == 1) 
                            { return '<span style="color: green"><i class="fa fa-check"> </i></span>';} 
                                else 
                            { return } '<span style="color: red"><i class="fa fa-times"> </i></span>'; } 
                    },
                    {"targets": [4], 
                        "render": function ( data, type, full, meta ) {

                            if(data == 1) 
                            { return '<span style="color: green"><i class="fa fa-check"> </i></span>';} 
                                else 
                            { return }'<span style="color: red"><i class="fa fa-times"> </i></span>'; } }
                    
                ]
        });
</script>

When I run the page I get a popup of

DataTables warning: table id=thetable - Requested unknown parameter '4' for row 0, column 4. For more information about this error, please see http://datatables.net/tn/4

Then the table rewnders correctly. No fields - espcially admin - are returning a blank.

26 Dec
1 year ago

jim1506 left a reply on Datatables And Conditional Images - 5.3

With a little bit of tinkering I got red for the crosses and green for the ticks:

 $('#dtable').DataTable({
        processing: true,
        serverSide: true,
        ajax: '{{ route('users.serverSide') }}',
        "columnDefs": [ {
            "targets": 4,   // choose the correct column
            "render": function ( data, type, full, meta ) {
                if(data == 1) 
                { return '<span style="color: green"><i class="fa fa-check"> </i></span>';} 
                    else 
                { return '<span style="color: red"><i class="fa fa-times"> </i></span>'; } }
        } ]
    });  

jim1506 started a new conversation Datatables And Conditional Images - 5.3

I have a simple table showing the users table, to which I have added an 'active' field with a value of 1 for active and 0 for inactive.

I have the following view (the jquery and datatables and pulled in the app view):

@extends('layouts.app')
@section('content')

<div class="panel panel-default" style="padding-left: 2em; padding-right: 2em">
  <div class="panel-heading">Users</div>
  <div class="panel-body"> 
     <table class="datatable" id="dtable" width="90%" align="center">
        <thead>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Created at</th>
            <th>active</th>
          </tr>
        </thead>
        <tbody>
        </tbody>
      </table>
  </div>
</div>

  <script>
    $(document).ready(function(){
      $('#dtable').DataTable({
            processing: true,
            serverSide: true,
            ajax: '{{ route('users.serverSide') }}'
        });
    });
  </script>
@endsection```

In web.php I have the following method to get the data:

Route::get('/users/serverSide', [ 'as' => 'users.serverSide', 'uses' => function () { $users = App\User::select(['id', 'name', 'email', 'created_at', 'active']);

    return Datatables::of($users)->make();
}

]);


All this works fine, but I would like to replace the 1 or 0 in the active table with either a tick or a cross, using either a site icon or Fontawesome.

Anyone point me in the right direction please? I know I could set up a view in mySQL but they tend to be slow.
12 Dec
2 years ago

jim1506 started a new conversation Relationship Returning A Count Rather Than Array

I have two tables - places and establishments. There is a relationship set up in the model which works fine.

In the Place model I have a relationship which is based on a foreign key Town_id

public function establishment()
    {
        //a place has many places
        return $this->hasMany('App\Establishment','Town_id');
    }  

I know I could simply count the array size but I am wondering if there is a more eloquent way of setting this up for a new function called, say, estab _count with the same relationsip?