uccdev

uccdev

Member Since 8 Months Ago

Experience Points 4,480
Experience Level 1

520 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 33
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

17 May
2 days ago

uccdev left a reply on Task Scheduling Runs Every Minute Despite My Directions

Having investigated, I believe it's not due to any of the code I wrote here, but how I called my scheduler from the server itself:

              * * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1

I should change the number from "1" to another value, according to how many minutes I want to run it for.

uccdev started a new conversation Task Scheduling Runs Every Minute Despite My Directions

Hi,

I'm scheduling my app/console/Kernel.php to run the following code every fifteen minutes:

       protected function schedule(Schedule $schedule)
       {
               Log::info('now im attmept schedule');
               $schedule->job(new ServerJob("hi"))->everyFifteenMinutes();
               Log::info('i doon');
       }

The problem is, this isn't running every fifteen minutes, it is running every ONE minute.

The schedule calls the following job:

     public function __construct($serveJob)
     {
           Log::info("Job constructor");
           $this->serveJob = $serveJob;
           self::findBBDirect();
           self::testEmail();
           Log::info("job's dun");
     }

That job's functions look, right now, like:

    public function testEmail() {
          Log::info("Test email");
          Mail::send("testCurl", [],
          function($message) { //use ($filePath)
            $message->to('[email protected]', 'Artisans Web')
            ->subject('Marco Polo');
            $message->from('[email protected]', 'Sample name');
          });
        }

        public function findBBDirect() {
          $token = $this->accessToken;
          $headers = ['Authorization: Bearer ' . $token];

          $curl = curl_init();
          $validReturn = true;
          $url = "https://my.instructure.com/api/v1/accounts/1/courses?per_page=100";

          curl_setopt_array($curl, [
            CURLOPT_RETURNTRANSFER => TRUE,
            CURLINFO_HEADER_OUT => TRUE,
            CURLOPT_URL => $url,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_SSL_VERIFYPEER => TRUE,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HEADER => TRUE,
            CURLOPT_RETURNTRANSFER, TRUE
          ]);
          if (curl_errno($curl)) {
            Log::info('Error:' . curl_error($curl));
          } else {
            Log::info('Yep, curl is fine');
          }

          $resp = curl_exec($curl);
          $header_size = curl_getinfo( $curl, CURLINFO_HEADER_SIZE );
          $header = substr( $resp, 0, $header_size );
          $body = substr( $resp, $header_size );
    
          $data = json_decode($body, true);
          $explData = explode("\n",$resp);
          $buttons = ["Current", "Next", "Prev", "First"];
          $links = $explData[15];
          $pageLinks = explode(",", $links);
          $bbData = array_fill(0, 4, null);
          $numBBs = 0;
          foreach ($data as $d) {
            if((array_key_exists("id", $d)) && (self::hasBBDirect($d["id"]))) {
              Log::info("found BB");
              $bbData[$numBBs] = $d["id"];
              $numBBs++;
            }
          }
          curl_close($curl);
    }

Any ideas why this would happen?

To clarify, I've seen this thread as well: https://laracasts.com/discuss/channels/general-discussion/task-scheduling-runs-every-minute-instead-of-the-time-that-i-set . But since I am not giving any specific cron directions, or usage, I am not sure the advice within is applicable here. I am extra unsure, in fact, since just two days ago, all was working as I had expected it to. That it isn't now, I don't know what to do.

Any help would be greatly appreciated

15 May
4 days ago

uccdev left a reply on Laravel Not Creating Log File?

The issue was simply that my Homestead virtual machine hadn't loaded properly. A simple restart did the trick.

uccdev started a new conversation Laravel Not Creating Log File?

I've got a laravel schedule running on my server, but despite successful execution, I am not getting a log file for today. I have log files for yesterday but not today.

Why does something like this happen? What can I do about it?

uccdev started a new conversation Schedule A Job From A Controller?

So I've got a server I want to schedule certain functions on. I've got a controller and functions in it. And I've got a Job that dispatches commands.

I know that my scheduler cannot call controller functions, it must call a job.

I know that I can put functions inside my job file, though such seems redundant, especially following the advice from this link, that says to have controllers call jobs: https://laracasts.com/discuss/channels/laravel/call-controller-method-inside-a-job-handle-method

So what is the conventionally best way? Is what I'm asking for in the title possible or recommended?

09 May
1 week ago

uccdev left a reply on How To Call A Controller Function From Schedule And Pass Parameters

@MARTINBEAN - Hey Martin, just saw this myself while having the same problem that wassim had. I'm learning about jobs and queues now from the documentation, but in the case of your example, can you describe for me what "new YourJobName" would look like?

03 May
2 weeks ago

uccdev started a new conversation Do I Need Cron To Use Schedulers On Homestead?

Hi,

I'm running laravel through a virtual machine run by homestead at the moment. I've set schedule = true in my Homestead.yaml and I've edited my schedule() function to run a simple email every ten minutes:

          protected function schedule(Schedule $schedule)
          {
                  $schedule->call('[email protected]')
                  ->everyTenMinutes();
          }

It doesn't seem to be enough, though, so I'm wondering if there's anything else I need to do? I haven't installed cron or called anything on the command line, I just have Homestead up and running.

P.S does it matter if I'm using windows if I want to install cron?

02 May
2 weeks ago

uccdev started a new conversation Do I Need Cron To Use Schedulers On Homestead?

Hi,

I'm running laravel through a virtual machine run by homestead at the moment. I've set schedule = true in my Homestead.yaml and I've edited my schedule() function to run a simple email every ten minutes:

                 protected function schedule(Schedule $schedule)
                 {
                         $schedule->call('[email protected]')
                         ->everyTenMinutes();
                 }

It doesn't seem to be enough, though, so I'm wondering if there's anything else I need to do? I haven't installed cron or called anything on the command line, I just have Homestead up and running.

P.S does it matter if I'm using windows if I want to install cron?

25 Apr
3 weeks ago

uccdev started a new conversation Write A Command Line Script In Laravel To Check Courses?

Hi, I'm trying to search every account in my endpoint https://my.test.instructure.com/api/v1/accounts/1/courses

I've written a laravel browser application that can let me check them individually, but now I need a command line script that, when automated, will comb through ALL the entries here, see if they have a certain folder, and then delete that folder if so.

I've checked laracasts and the broader web, but so much of their information seems to be about main laravel web applications (which isn't what I'm looking for). Does anyone have any advice how best I might go about solving this? Any help would be kindly appreciated.

24 Apr
3 weeks ago

uccdev left a reply on Laravel Controller Is Not Returning To View?

@SNAPEY - Snapey, sorry for the delay, we're on different timezones and I was well out of the office at this point. Indeed, my findFolderPageNum was using self::findBBDirect($thing) But after changing it to: return $this->findBBDirect($stuff); The view is being returned at long last. Things are now all working as they should be. Thank you!

23 Apr
3 weeks ago

uccdev left a reply on Laravel Controller Is Not Returning To View?

@SNAPEY - Yes to both, Snapey/ "Going to view Folder" appears, though that is the last bit of display to appear.

I got to function "findBBDirect" out of a route direct, yes. To be precise:

                     Route::get('/folder', '[email protected]')
18 Apr
1 month ago

uccdev started a new conversation Laravel Controller Is Not Returning To View?

My problem is simple. On the latest version of laravel, my controller function is not returning to the given view. here is all I have.

my controller's function:

       public function findBBDirect($pageNumber) {
           $token = $this->accessToken;
           $headers = ['Authorization: Bearer ' . $token];

           $curl = curl_init();
           $loop = 1;
           $validReturn = true;
           $url = "https://my.url.com"

             curl_setopt_array($curl, [
               CURLOPT_RETURNTRANSFER => TRUE,
               CURLINFO_HEADER_OUT => TRUE,
               CURLOPT_URL => $url,
               CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
               CURLOPT_SSL_VERIFYPEER => TRUE,
               CURLOPT_HTTPHEADER => $headers,
               CURLOPT_HEADER => TRUE,
               CURLOPT_RETURNTRANSFER, TRUE
             ]);
             if (curl_errno($curl)) {
               echo 'Error:' . curl_error($curl) . "<br>";
             } else { echo " all good<br>"; }
             $resp = curl_exec($curl);

             $header_size = curl_getinfo( $curl, CURLINFO_HEADER_SIZE );
             $header = substr( $resp, 0, $header_size );
             $body = substr( $resp, $header_size );

             $data = json_decode($body, true);

             $explData = explode("\n",$resp);
             $buttons = ["Current", "Next", "Prev", "First"];
             $links = $explData[15];
             $pageLinks = explode(",", $links);
             $pages = array_fill(0, 4, null); //the page URL links
             $rels = array_fill(0, 4, null); //references (i.e "current", "next", "prev", "last")
             $pageNums = array_fill(0, 4, null); //amount of pages
             $i = 0;

             foreach($pageLinks as $p) {
               echo $pageLinks[$i] . "<br>";
               $pages[$i] = AppHelper::instance()->get_string_between($pageLinks[$i], "<", ">");
               $rels[$i] = AppHelper::instance()->get_string_between($pageLinks[$i], 'rel="', '"');
               $pageNums[$i] = AppHelper::instance()->get_string_between($pageLinks[$i], "?page=", "&");
               $i++;
             }

             if (array_key_exists("errors", $data)) {
               $validReturn = false;
               echo "Invalid page found. Ending after loop $loop</br>";
             }
             else {
               foreach ($data as $d) {
                 if((array_key_exists("id", $d)) && (self::hasBBDirect($d["id"]))) {
                   echo "BB_Direct folder FOUND in course " . $d["id"] . "</br>";
                 } else {
                   echo "No BB_Direct folder found in course " . $d["id"] . "<br>";
                 }
               }
             }
             curl_close($curl);
             echo "<h4>Going to view Folder</h4>"; //THE LAST line reached
       
             return view('folder')
  ->with("data", $data)
  ->with("rels", $rels)
  ->with("pages", $pages)
  ->with("pageNums", $pageNums);
             echo "<h4>Didn't go?</h4>";
         }

And my view, "folder.blade.php":

       <html>
    <head>
        <title>Placeholder</title>
    </head>
    <body>
        <h1>Hi</h1>
    </body>
       </html>
       
       

Why do I never get to the view? The code gets to the "return" call, and stops. What's wrong?

08 Apr
1 month ago

uccdev started a new conversation Can I Check Each Of My Courses For A Certain Folder More Efficiently Than This?

Hi, I am checking all the courses in my Canvas database to see which ones have a certain folder. Let's call this folder "BB_Direct."

At the moment, using cUrl requests like below, I check the accounts/number/courses endpoint to retrieve all the courses: ``$loop = 1; //increments with each loop $validReturn = true;

while($validReturn) {
  curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => true,
    CURLINFO_HEADER_OUT => true,
    CURLOPT_URL => "https://my.test.instructure.com/api/v1/accounts/$loop/courses?by_subaccounts[100]&per_page=100",//?by_subaccounts[95]&per_page=100/",//'https://ucc.test.instructure.com/api/v1/courses',
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_CUSTOMREQUEST, 'GET',
    CURLOPT_RETURNTRANSFER, true
  ]);

$resp = curl_exec($curl); $data = json_decode($resp, true); if (array_key_exists("errors", $data)) { //assuming that there are NO valid pages after the latest retrieved one that returns "error" $validReturn = false; echo "Invalid page found. Ending after loop $loop"; } else { echo "Loop $loop "; //dd($data); //dd($data); foreach ($data as $d) { if((array_key_exists("id", $d)) && (self::hasBBDirect($d["id"]))) { //important line echo "BB_Direct folder FOUND in course " . $d["id"] . ""; } else { echo "No BB_Direct folder found in course " . $d["id"] . ""; } } $loop++; }``

See the "self::hasBBDirect($d["id"])" line? That directs to a helper function to check if any courses under the returned course ID have the folder I'm looking for:

``public function hasBBDirect($courseID) { $token = "insert_token_here"; $headers = ['Authorization: Bearer ' . $token]; $curl = curl_init(); $url = "https://my.test.instructure.com/api/v1/courses/$courseID/folders/by_path/BB_Direct"; //"BB_Direct" = the folder I'm looking for

curl_setopt_array($curl, [
  CURLOPT_RETURNTRANSFER => true,
  CURLINFO_HEADER_OUT => true,
  CURLOPT_URL => $url,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_SSL_VERIFYPEER => true,
  CURLOPT_HTTPHEADER => $headers,
  CURLOPT_RETURNTRANSFER, true
]);

$resp = curl_exec($curl);
$data = json_decode($resp, true);
if(array_key_exists("errors", $data)) {
  return False;
} else { //presumably, the given course has a BB_Direct folder after all then
  return True;
}

}``

Now, the code I have listed works, it does what I want it to do. But the dataset I am working on has 7000 entries in it, so this takes a lot of time to compute. My question is, how can I OPTIMISE this? Can I find a certain folder in my list of courses any more efficiently?

Any thoughts anyone could lend me would be greatly appreciated

02 Apr
1 month ago

uccdev left a reply on Compare Dates That Are In The "2019-04-01T15:25:29Z" Format?

@FTIERSCH - It works! Thank you very much.

If anyone tries this and gets "Carbon not found", include the library with "use Carbon\Carbon;" That worked for me.

uccdev left a reply on Compare Dates That Are In The "2019-04-01T15:25:29Z" Format?

@FTIERSCH - Thanks, trying this now. Seem to be getting "Class 'App\Http\Controllers\Carbon' not found" errors right now.

uccdev started a new conversation Compare Dates That Are In The "2019-04-01T15:25:29Z" Format?

Hi, I need to compare two dates to see which one is the newest.

The dates aren't in a conventional format, though, they're formatted like in the title.

So say I have a date "2019-04-01T15:25:29Z". I want to compare that with "2019-04-01T19:00:12Z" and tell me which one is more recent.

Does anyone know how Laravel can manage such a comparison? I'd sincerely appreciate it.

11 Jan
4 months ago

uccdev left a reply on Laravel - Route Based On Form Submit?

@CRONIX - That did the trick, thank you very much!

10 Jan
4 months ago

uccdev started a new conversation Laravel - Route Based On Form Submit?

I have one HTML form, with many different submit buttons.

Each submit button has a value. For instance, the value of the first button may be simply "submit", while the value of the next might be "12".

Based on which value the submit button is given, I want my web.php route file to direct it to a different function.

However, I don't know how. Any advice? I would dearly appreciate any help here

uccdev left a reply on Laravel Pagination - Changing The Page Makes My Query Vanish?

@NIKOS - That did, thank you! What I changed was in the view:

        {{$postmen->appends(request()->query())->links() }}

Now I'm paginating everything I want to be!

09 Jan
4 months ago

uccdev started a new conversation Laravel Pagination - Changing The Page Makes My Query Vanish?

So I'm writing a page using Laravel that calls data from my database.

The database returns all its data in the form of a paginated table.

The user is given five fields and a submit box. Every field is optional, so they can be as specific as they like in their query. If no values at all are called, then it is a general search of the database.

My Controller's query looks like so:

 $postmen = DB::table('postmen')
   ->join('cats', 'postmen.cat_id', '=', 'cats.cat_id')
   ->join('reg_status', 'postmen.status_id', '=', 'reg_status.status_id')
   ->select('postmen.postmen_id', 'postmen.forename', 'postmen.surname',
    'cats.description AS catdesc', 'reg_status.description AS regdesc')
    ->where(function ($query) use ($request) {
      if (!empty($request->forename)) {
        $query->where('postmen.forename', $request->forename);
      }
      if (!empty($request->surname)) {
        $query->where('postmen.surname', $request->surname);
      }
      if (!empty($request->cat_id)) {
        $query->where('postmen.cat_id', $request->cat_id);
      }
      if (!empty($request->status_id)) {
        $query->where('postmen.status_id', $request->status_id);
      }
      if (!empty($request->postmen_id)) {
        $query->where('postmen.postmen_id', $request->postmen_id);
      }
    })
   ->paginate(10);

Now, the above code works, and returns for me a query with the values I want.

So, on the view side? I have a table that gives me the following:

    <form action="searchCriteria" method="get">
      @csrf
           <label for="forename">Forename: </label>
           <input type="text" name="forename">

           <label for="surname">Surname: </label>
           <input type="text" name="surname">

          <label for="cat_id">Cat: </label>
            <select name="cat_id">
              <option name="---" value=0>---</option>
              <option name="Black" value=1>Black Cat</option>
              <option name=”White” value=2>White Cat</option>
              <option name=”BlackWhite” value=3>Black and White Cat</option>
            </select>
    
          <label for="status">Status: </label>
            <select name="status_id">
              <option name="---" value=0>---</option>
              <option name="Injured" value=1>Injured</option>
              <option name="Working" value=2>Working</option>
              <option name="Holiday" value=3>Holiday</option> 
            </select>

           <label for="postman_id">Postman ID: </label>
           <input type="number" name="postman_id">
         
    
      <input type="submit" name="submit" value="Submit">

      <div class="form-group">
        <table id="postmanTable" data-page-length='5' cellspacing="0"
class="table table-bordered table-striped table-hover table-condensed"
role="grid">
        <!--Default table headers-->
          <thead class="thead-dark">
            <tr>
              <th scope="col">Postman ID:</th>
              <th scope="col">Name:</th>
              <th scope="col">Surname:</th>
              <th scope="col">Cat:</th>
              <th scope="col">Status:</th>
            </tr>
          </thead>
          <tbody>
    <!--Display all the data from the query-->  
            @if( !empty($postmen))
              @foreach ($postmen as $postman)
                <tr>
                  <td>{{$postman->postman_id}}
                    <input type='submit' name='submit' value={{$postman->postman_id}}></input>
                  </td>
                  <td>{{$postman->forename}}</td>
                  <td>{{$postman->surname}}</td>
                  @if( !empty($course))
                    <td>{{$course->description}}</td>
                  @else
                    <td>{{$postman->catdesc}}</td>
                  @endif
    
                  @if(!empty($status))
                    <td>{{$status->description}}</td>
                  @else
                    <td>{{$postman->regdesc}}</td>
                  @endif
                </tr>
              @endforeach
            @else
              <tr>
                <td>{{$postman->postman_id}} <input type='submit' name='submit' value={{$postman->postman_id}} ></input> </td>
                <td>{{$postman->forename}}</td>
                <td>{{$postman->surname}}</td>
                <td>{{$postman->catdesc}}</td>
                <td>{{$postman->regdesc}}</td>
              </tr>
            @endif


          </tbody>
        </table>
    
        @if(!empty($postmen) )
          @if ($postmen->hasMorePages())
            {{$postmen->links()}}
          @endif
        @else
          <h4>No postmen available under this query</h4>
        @endif
      </div>
    </form>

This also gives me the table I want, fully paginated, with paginated links to match.

So what is the problem?

It's when I try to go to a different page in the query other than the first. It thinks I should be clicking the Submit button thanks to my controller's validation (unshown) requiring the submit button be clicked.

And when I remove the validation so I can click the button as normal? Well the query completely changes, from a specific query to one that has no queries at all. If I query for all postmen with the forename "Tom", then look at page 2 of the results, I instead get every postman with any name at all, not just Tom. That shouldn't be the case.

Any advice? Such would be greatly appreciated if you could.

08 Jan
4 months ago

uccdev left a reply on Laravel Pagination Causes MethodNotAllowedHttpException ?

I found the error. A form the pagination used that I had overlooked was still using "POST". When I changed it to "GET", the timeout error vanished. Thank you for all your help!

04 Jan
4 months ago

uccdev left a reply on Laravel Pagination Causes MethodNotAllowedHttpException ?

@SNAPEY - Yes, Snapey; with the commented parts removed, it is just like my default search, and the pagination works perfectly. Unfortunately, my final site needs to have a query that can be optionally specific, like the commented parts try to do

03 Jan
4 months ago

uccdev left a reply on Laravel Pagination Causes MethodNotAllowedHttpException ?

@SNAPEY - public function searchCriteria(Request $request) { //DO NOT USE "required", as no field here is (besides 'submit') $validated = Validator::make($request->all(), [ "submit" => "required", "forename" => "nullable|regex:/^[a-zA-Z\s’'.-]+$/", "surname" => "nullable|regex:/^[a-zA-Z\s’'.-]+$/", "cat_id" => "between:0,4", //[Rule::in([1, 2, 3, 4, 5]) ], "status_id" => "between:0,5",//[Rule::in([1, 2, 3, 4]) ], "postmen_id" => "nullable|regex:/^[0-9]+$/" ]); $data = $request->all(); $errors = $validated->errors(); if($validated->fails()) { return redirect()->back()->withInput($request->all())->withErrors($errors); }

try {

  $postmen = DB::table('postmen')
  ->join('cats', 'postmen.cat_id', '=', 'cats.cat_id')
  ->join('reg', 'postmen.status_id', '=', 'reg.status_id')
  ->select('postmen.postmen_id', 'postmen.forename', 'postmen.surname',
   'cats.description AS catdesc', 'reg.description AS regdesc')
   ->where(function ($query) use ($request) {
     if (!empty($request->forename)) {
       $query->where('postmen.forename', $request->forename);
     }
     if (!empty($request->surname)) {
       $query->where('postmen.surname', $request->surname);
     }
     if (!empty($request->cat_id)) {
       $query->where('postmen.cat_id', $request->cat_id);
     }
     if (!empty($request->status_id)) {
       $query->where('postmen.status_id', $request->status_id);
     }
     if (!empty($request->postmen_id)) {
       $query->where('postmen.postmen_id', $request->postmen_id);
     }
   })
  ->simplePaginate(10);


  if(isset($request->cat_id)) {
    $cat = DB::table(‘cats’)
      ->where('cat_id', $request->cat_id)
      ->first();
  }
  if(isset($request->status_id)) {
    $status = DB::table(‘reg')
      ->where('status_id', $request->status_id)
      ->first();
  }
  /*
  Deals with the "cat" and "status" fields. Returns data to the view depending on whether any of them are set. Also tells the 'postmen' view that special search results are used, by passing it $criteria
  */
  if (empty($postmen)) {
    return PostController::neutralSearch();
  }
  else {
    $criteria = True;
    $idFail = False;
    if (isset($cat) && !(isset($status))) {
      return view('postmen')->with('postmen', $postmen)
      ->with('course', $cat)
      ->with('criteria', $criteria)
      ->with('idFail', $idFail);
    }
    else if ((isset($status)) && !(isset($cat))) {
      return view('postmen')->with('postmen', $postmen)
      ->with('status', $status)
      ->with('criteria', $criteria)
      ->with('idFail', $idFail);
    }
    else if ( (isset($status)) && (isset($cat)) ) {
      if (!(isset($postmen)) || (empty($postmen))) {
        PostController::neutralSearch();
      }
      return view('postmen')->with('postmen', $postmen)
      ->with('course', $cat)
      ->with('status', $status)
      ->with('criteria', $criteria)
      ->with('idFail', $idFail);
    }
    else {
      return PostController::neutralSearch();
      }
      return view('postmen')->with('postmen', $postmen);
    }
  }
} catch (Exception $ex) { //(Illuminate\Support\Facades\Validator $ex){
  dd($ex->getMessage());
  // Note any method of class PDOException can be called on $ex.
  return redirect()->back()->withInput($request->all())->withErrors($errors);
}

}

02 Jan
4 months ago

uccdev left a reply on Laravel Pagination Causes MethodNotAllowedHttpException ?

@MUNAZZIL - Sadly not yet, no. None of the provided solutions have worked; my pagination page still times out

uccdev left a reply on Laravel Pagination Causes MethodNotAllowedHttpException ?

@JLRDW - Thank you for your post. Sorry for the delay; I'd finished up for Christmas then.

I've tried the code in your first post, and gotten this error:

   syntax error, unexpected '->' (T_OBJECT_OPERATOR)

I'm not entirely sure about that. On the first "->where" in the first "if". It's not the extra ")" in the if, in case you were thinking of that.

Thank you very much for all of those links, but I admit, I'm not very sure how relevant some of them are. How are you suggesting I use advanced joins, for instance, to decide whether to optionally use elements? And the laracasts thread just says from what I see to 'use joins' some more.

Any advice?

21 Dec
4 months ago

uccdev left a reply on Laravel Pagination Causes MethodNotAllowedHttpException ?

@MUNAZZIL - I tried the first change, and got no difference; still a timeout.

Then I commented those two lines out and used Route::resource instead. I got an error exception:

       BadMethodCallException

Method App\Http\Controllers\CardController::store does not exist.

uccdev left a reply on Laravel Pagination Causes MethodNotAllowedHttpException ?

@MUNAZZIL - The web.php code:

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

uccdev left a reply on Laravel Pagination Causes MethodNotAllowedHttpException ?

@MUNAZZIL - I'm not sure how to open the laravel console. I'm working with my text editor at the moment.

Also, I have a route::get and a route::post for this page.

uccdev left a reply on Laravel Pagination Causes MethodNotAllowedHttpException ?

@JLRDW - Where do you suggest making that change? In my controller or my view? if you mean the controller, then it is already there:

      $postmen = DB::table('postmen')
       ...
       ...->paginate(10);
20 Dec
4 months ago

uccdev left a reply on Laravel Pagination Causes MethodNotAllowedHttpException ?

@VILFAGO - I think that worked. I'm not getting the same dd error page anymore. What I am getting instead, tragically, is a page timeout. Apparently my page has redirected me too many times?

uccdev left a reply on Laravel Pagination Causes MethodNotAllowedHttpException ?

@VILFAGO - I had been using exclusively POST

uccdev left a reply on Laravel Pagination Causes MethodNotAllowedHttpException ?

@JLRDW - Do you mean the append to pagination code? Like: {{ $users->appends(['sort' => 'votes'])->links() }} I'm not sure how that should look. Say my pagination is like this:

                       {{ $postmen->links() }}

What should I append to that?

uccdev started a new conversation Laravel Pagination Causes MethodNotAllowedHttpException ?

So I am working on a site that paginates two different types of DB queries.

The first is a generic "get everything" query. The second has specific checks (e.g "WHERE name = 'John'")

Both are done with simplePaginate(num); I'll show my code if it's considered relevant.

The first works perfectly fine. BUT the second throws an error whenever I use Next or Previous.

               Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException

No message

Does anyone know why this happens?

uccdev left a reply on Paginate A Laravel Query With Optional Parameters?

@REALRANDYALLEN - Randy, that was exactly what I was looking for. Thank you very much!

I've gotten a different error on top of that now, where the standard "Next" button causes a MethodNotAllowedHttpException, but that's a separate issue. Your solution solves this problem.

19 Dec
5 months ago

uccdev started a new conversation Paginate A Laravel Query With Optional Parameters?

I'm trying to make a search table with criteria for people to look up - name, surname, ID, course, etc. When they put in their specific values, laravel will paginate the results in a table and show them.

Sounds straightforward, right? The trick is that every field is optional. So if a field is included, it must be searched based on that value. If a field is left blank, then the query must not consider that value in its search (which is to say, the excluded fields can be of any value, only the included fields must be specific).

My solution below, for this specific purpose, does exactly that:

       $name   = ($request->name != '' ? " AND  post.name = '" . $request->name . "'" : "");
       $surname    = ($request->surname != '' ? " AND post.surname = '" . $request->surname . "'" : "");
       $cats_id  = ($request->cats_id > 0 ? " AND post.cats_id = " . $request->cats_id : "" );
       $status_id  = ($request->status_id > 0 ? " AND post.status_id = " . $request->status_id : "");
       $postmen_id = ($request->postmen_id > 0 ? " AND post.postmen_id = " . $request->postmen_id : "");


       $postmen =
    DB::select("SELECT TOP 50
      post.postmen_id, post.name, post.surname, cat.description AS catdesc, reg.description AS regdesc
      FROM postmen post
      INNER JOIN cats as cat
        ON (cat.cats_id = post.cats_id)
      INNER JOIN registration_status as reg
        ON (reg.status_id = post.status_id)
      WHERE active_flag = 'Y'
      " . $name . $surname . $cats_id . $status_id . $postent_id .
  "");

      return view('postmen_table')->with('postmen', $postmen);

The above code works. So what's the problem? Pagination. In my view, when I call:

        {{ $students->links() }}

I get this error: "Call to a member function links() on array"

I know I can get around this with a DB::table query, which might look like this:

             $postmen = DB::table('postmen')
  ->join('cats', 'postmen.cats_id', '=', 'cats.cats_id')
  ->join('registration_status', 'postmen.status_id', '=', 'registration_status.status_id')
  ->select('postmen.postent_id', 'postmen.name', 'postmen.surname',
   'cats.description AS catdesc', 'registration_status.description AS regdesc')
  ->simplePaginate(30);

However, this doesn't have the flexibility of the first solution; I have to query by every field, even the ones that the user leaves blank. I know how to express this in DB::select, but not in DB::table, and that's where I am stuck.

Does anyone know anything I could do to remedy this? Any suggestions would be greatly appreciated.

14 Dec
5 months ago

uccdev left a reply on Paginate A Database's Complete Results?

@VILFAGO - I'd like to try that, but when I try this:

           {{$dairies->links}}

I get this:

            "Undefined property: Illuminate\Pagination\Paginator::$links..."

I'm using Paginator in my namespace with the following line:

              "use Illuminate\Pagination\Paginator;"

But I still get the error

uccdev left a reply on Paginate A Database's Complete Results?

@REALRANDYALLEN - I see. I guess part of my problem is I don't have the buttons to cycle through paginations. I don't have the Next and Prev buttons to cycle through the amount of entries overall - how exactly should I set those up? The pagination documentation doesn't seem to cover them

uccdev left a reply on Paginate A Database's Complete Results?

@THOASTY - Indeed, but I need a step beyond that. I need to be able to go from the current 50 to the next 50, when the user presses the Next button, and vice versa for the Previous button. Any advice?

uccdev left a reply on Paginate A Database's Complete Results?

@ZION - Thank you very much, this looks to be on the money for what I want! I can't test it just yet since my server is currently down, but once it's up, I'll test it and update you

uccdev started a new conversation Paginate A Database's Complete Results?

Hi, I need help with paginating my database.

Basically, I want to do a complete query from my DB, and I want to chunk it off so that only certain sections of it are given at a time - the rest can be scrolled through via pagination.

e.g:

   $dairies = DB::table('dairies')
select('name', 'stock')
->get();

This would return every entry in the 'dairies' table, all 20,000+ of them.

I know of the "->paginate(num)" extension I can add to my DB::table, like so instead of 'get': ->paginate(50);

But what I need to do isn't simply to paginate the result. I need to spread it out so that, rather than load all 100,000+ entries in the DB, I only load, say, 50 at a time, and hitting the 'next' or 'previous' button will get the next batch of 50 after that.

Does anyone know how to do this? If you could spare the time, your help would be greatly appreciated!

05 Dec
5 months ago

uccdev left a reply on Insert Adds Many Entries Instead Of Only One?

@REALRANDYALLEN - Just wrote up a statement that worked out grand.

 $students = DB::select("SELECT TOP 50
              stud.id, stud.forename, stud.surname, crs.description AS crsdesc, reg.description AS regdesc
              FROM myTable stud
              INNER JOIN crsTable as crs
                ON (crs.course_id = stud.course)
              INNER JOIN regTable as reg
                ON (reg.status_id = stud.status)
              WHERE active_flag = 'Y'
              " . $forename . $surname . $course . $status . $id.
              "");

Thanks for your help!

uccdev left a reply on Insert Adds Many Entries Instead Of Only One?

@REALRANDYALLEN - I think I see, but can I ask how would you suggest I restructure the query with joins?

uccdev left a reply on Insert Adds Many Entries Instead Of Only One?

@REALRANDYALLEN - $forename = ($request->forename != '' ? " AND stud.forename = '" . $request->forename . "'" : ""); $surname = ($request->surname != '' ? " AND stud.surname = '" . $request->surname . "'" : ""); $course = ($request->course_id > 0 ? " AND stud.course = " . $request->course : "" ); $status = ($request->status_id > 0 ? " AND stud.status = " . $request->status : ""); $id = ($request->id > 0 ? " AND stud.id = " . $request->id : "");

  $students = DB::select("SELECT TOP 50
              stud.student_id, stud.forename, stud.surname, crs.description AS crsdesc, reg.description AS regdesc
              FROM myTable stud, crsTable crs, regTable reg
              WHERE active_flag = 'Y'
              " . $forename . $surname . $course . $status . $id .
              "");

//shows the user based on specific criteria (e.g search by ID, search by first name, etc.)

uccdev started a new conversation Insert Adds Many Entries Instead Of Only One?

I'm interfacing with a database in my Laravel controller, where I want to insert given data into a database.

My insert statement is like this:

$insert = DB::table('myTable')->insert( [ 'id' => $data['id'], 'forename' => $data['forename'], 'surname' => $data['surname'], 'course' => $data['course'], 'status' => $data['status'], 'photo' => $data['photo'] ] );

This should create only one insertion, to the best of my understanding, since I am only entering the one value. However, when the page tries to display the results when I search based on ID alone, I get dozens and dozens of entries! One for each combination of "course" and "status" (where those two are fixed fields, values between 1 and 5).

Note that I am not working with a model, just putting the input straight into a controller.

I have also tried the alternative laravel function, DB::insert...

$insert = DB::insert("INSERT INTO myTable (id, forename, surname, course, photo) VALUES (?, ?, ?, ?, ?)", [$data['id'], $data['forename'], $data['surname'], $data['course'], $data['status']] );

...But this runs into the same problem.

Furthermore, when I check my database separately (via a "SELECT * FROM myTable WHERE id = 888;") then I don't get many entries - I get only one.

Yet my webpage shows as many as 40 entries for that same ID, for a single iteration of a given field - when only one should exist at all.

Any advice? I'd be most grateful for any help someone could give me here.