clat23

Experience

10,280

0 Best Reply Awards

  • Member Since 1 Year Ago
  • 88 Lessons Completed
  • 0 Favorites

17th August, 2017

clat23 started a new conversation Session Variables Not Saving / Persisting After Redirect • 11 hours ago

Comment.php

public function store($data)
    {
        $comment = new Comment;
        $comment->title = $data->title;
        $comment->body = $data->body;
        $comment->save();
        session(['commentTitle' => $data->title]);
        session(['commentBody' => $data->body]);
        dd(session('commentTitle')); // This dumps the title string as expected...
        return redirect()->action([email protected]');

CommentsController.php

public function index()
{
    $comments = Comment::get();

    dd(session('commentTitle')); // This dumps null...?

    return view('/comments/index')->with([
        'comments' => $comments,
    ]);

Any idea why the session variables are not persisting?

28th July, 2017

clat23 started a new conversation Chaining Event Handlers? • 2 weeks ago

I would like to present multiple thumbnail images on a Laravel blade view. Each thumbnail, when clicked, opens a modal. Each modal would have code to adjust (crop, flip, rotate) that image. I am able to implement this for the first image, however the image adjuster code for the remaining images do not execute. Here's my code:

create.blade.php:

@extends('spark::layouts.app')
@section('content')
...
<!-- Some HTML code here for the view -->
...
<!-- Image Thumbnails as modal links -->
@if (isset($imageNames))
    @foreach ($imageNames as $imageName)
        <a href="#imageCropper-{{ $imageName }}" role="button" data-toggle="modal">
            <img class="img-thumbnail" style="height:100px;width:100px" src="/storage/images/{{ $imageName }}.jpg">
        </a>
    @endforeach
@endif 

<!-- Modals -->
@if (isset($imageNames))
    @foreach ($imageNames as $imageName)
        <div class="modal fade" id="imageCropper-{{ $imageName }}" role="dialog" aria-labelledby="modalLabel" tabindex="-1">
            <div class="modal-dialog modal-lg" role="document">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title" id="modalLabel">Adjust Image</h>
                </div>
              <div class="modal-body">
                <!-- Content -->
                  <div class="row">
                    <div class="col-md-12">
                      <div class="img-container">
                        <img id="image-{{ $imageName }}" src="/storage/images/{{ $imageName }}.jpg" alt="Picture">
                      </div>
            ...
              <!-- (truncated) Other image adjuster components here -->
            ...
                    </div>
                  </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
          </div>
      </div>
    @endforeach 
@endif 

@section('javascripts')
    <!-- Image Adjuster Scripts -->
    <script src="/js/cropper.js"></script>
    <script type="text/javascript">
    // Put all image names into array
    @if(isset($imageNames))
        var imageNames = [
        @foreach ($imageNames as $imageName)
            "{{ $imageName }}", 
        @endforeach
        ];
    @endif
    </script>
    <script src="/js/main.js"></script>
@endsection

main.js

window.addEventListener('DOMContentLoaded', function () {

  'use strict';

  var cropper;
  var URL = window.URL || window.webkitURL;
  var container = document.querySelector('.img-container');

  // Image adjuster code here...

  // Event handler for each thumbnail image clicked
  for (var i = 0; i < imageNames.length; i++) {
    var imageName = imageNames[i];
    $('#imageCropper-' + imageName).on('shown.bs.modal', function () {
      cropper = new Cropper(image, options);
    }).on('hidden.bs.modal', function () {
      cropper.destroy();
    });
  }

I am new to javascript and my guess is that I am not handling the multiple handlers the correct way. How would I go about this?

20th July, 2017

clat23 started a new conversation Is AJAX The Right Solution? • 3 weeks ago

I have a form that a user chooses a category from a category tree. The external API I'm using requires separate calls to their API based on the parent categories.

The way I'm handling this right now is a <select>' tag that contains options for the top level parent categories. The' submits the form onchange which sends a GET request to the API to retrieve the children categories based on the selected parent. This continues to happen with subsequent parent/children until I've reached my leaf category.

I have that working and it seems to be working fine. However my code is a mess. It's almost impossible to add other form elements to the page. The other downside is that the user experience isn't as nice as I'd like as the page has to reload every time the user selects a parent category.

Is AJAX the best answer? I have no knowledge of AJAX, before I sit down and learn it, I'd like some feedback to this idea.

13th July, 2017

clat23 started a new conversation Is It Possible To Specify An HTTP Method In A Spark Notification? • 1 month ago

I'm using Spark notifications as documented here:

https://spark.laravel.com/docs/4.0/notifications

Here's my code block to create the notification:

            $this->notifications->create($listing->user, [
                'icon' => 'fa-exclamation-triangle',
                'body' => "My message to the user here",
                'action_text' => 'Reactivate Post',
                'action_url' => '/posts/' . $post->id . '/reactivate',
            ]);

Here's my route:

Route::post('/posts/{post}/reactivate', [email protected]')->where('post', '[0-9]+')->middleware('postToReactivateValid');

I'm getting a "MethodNotAllowedHttpException". This is because the action_url link is sending the request with a GET http method and my route accepts a POST http method.

Is there anywhere in creating the Spark notification to specify the HTTP method to use?

19th June, 2017

clat23 left a reply on Flashing Works Flawlessly On Development, But Fails On Production • 1 month ago

I uninstalled my repository from the server and reinstalled it (Laravel Forge). This solved my flash failing issues. I don't know exactly what it was that was causing it, but this fixed it.

17th June, 2017

clat23 left a reply on Flashing Works Flawlessly On Development, But Fails On Production • 2 months ago

@Snapey No errors in console. Flash item is not listed in the browser source. I am using Laravel Forge.

15th June, 2017

clat23 started a new conversation Flashing Works Flawlessly On Development, But Fails On Production • 2 months ago

I'm using this package: https://github.com/laracasts/flash

SettingsController.php:

    public function setTimezone(SetTimezone $request)
    {
        $newTimezone = request()->timezone;
        Auth::user()->setTimezone($newTimezone);
        flash('Your timezone has been set.', 'success');
        return redirect()->action([email protected]');
    }

In my homestead development environment I see the flash message. However in production, the flash message does not appear when the user sets their timezone.

The only thing I can think of, is that I was running the 2.x version of laracasts/flash and had previously updated to 3.0. But I ran composer update on my production server and verified that the 3.0 version of laracasts/flash was installed. So that can't be it right?

I attempted to use Laravel's built-in flash component by modifying the above code to this:

    public function setTimezone(SetTimezone $request)
    {
        $newTimezone = request()->timezone;
        Auth::user()->setTimezone($newTimezone);
        $request->session()->flash('status', 'Your timezone has been set.');
        return redirect()->action([email protected]');
    }

(https://laravel.com/docs/5.4/session#flash-data)

Still I did not see any flash messages.

I don't really know where to look to diagnose this issue. Anyone have any ideas?

8th June, 2017

clat23 left a reply on Unable To Get Spark Notifications To Work... • 2 months ago

Nevermind, I figured it out. I instantiated it like this:

$handle = \App::make('App\ResponseErrorHandler');
$handle->error_931;

Thank you, thank you, thank @tekmi !!!

clat23 left a reply on Unable To Get Spark Notifications To Work... • 2 months ago

@tekmi Thank you and yes I watched those episodes when I was starting out with Laravel. Back then, it didn't make sense because I was so new. I watched it again today and it made more sense. So thank you for your guidance.

I made a few adjustments based on those videos and I now get this when I run dd(App::make('App\ResponseErrorHandler'));:

ResponseErrorHandler {#254 ▼
  +"notifications": NotificationRepository {#256}
}

But I still have a problem. When I run (new ResponseErrorHandler)->error_931;, I still get:

Type error: Too few arguments to function App\ResponseErrorHandler::__construct(), 0 passed

So then I tried changing it to run this (new ResponseErrorHandler(new NotificationRepository()))->error_931();, but I get this error:

[Symfony\Component\Debug\Exception\FatalThrowableError] Class 'App\NotificationRepository' not found

So I tried fixing it by adding use Laravel\Spark\Contracts\Repositories\NotificationRepository;, but then I got this error:

[Symfony\Component\Debug\Exception\FatalThrowableError] Cannot instantiate interface Laravel\Spark\Contracts\Repositories\NotificationRepository

I'm thinking that I am not instantiating it correctly now that I have registered ErrorHandlerServiceProvider?

I am using the magic method __get as you recommended to me here: https://laracasts.com/discuss/channels/laravel/handling-errors-from-an-outside-api

On your first reply to me in this discussion you said:

in this case you won't need to instantiate it by using new ResponseErrorHandler like you were doing.

How would I now instantiate it?

...Thank you again for being so helpful!

clat23 left a reply on Unable To Get Spark Notifications To Work... • 2 months ago

Thank you @tekmi I've created a service provider for ResponseErrorHandler by running:

php artisan make:provider ResponseErrorHandlerServiceProvider

Here's the ResponseErrorHandlerServiceProvider:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

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

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('App\ResponseErrorHandler', function ($app) {
            return new ResponseErrorHandler;
        });
    }
}

I then added App\Providers\ResponseErrorHandlerServiceProvider::class, to config\app.php

I still get the same error:

Type error: Too few arguments to function App\ResponseErrorHandler::__construct(), 0 passed

I noticed you mentioned:

in this case you won't need to instantiate it by using new ResponseErrorHandler like you were doing.

I am still instantiating in that way. Once it's been registered as a service provider, how would I now instantiate it?

Also, do I have the correct binding in the register method of my service provider?

I'm sorry for the many questions, this is my first time writing a service provider and registering it. Thank you for your help!

clat23 started a new conversation Unable To Get Spark Notifications To Work... • 2 months ago

I am following this documentation: https://spark.laravel.com/docs/4.0/notifications

ResponseErrorHandler.php

<?php

namespace App;

use Laravel\Spark\Contracts\Repositories\NotificationRepository;

class ResponseErrorHandler
{
    public function __construct(NotificationRepository $notifications)
    {
      $this->notifications = $notifications;
    }
    
    public function __get($error)
    {
        if (method_exists($this, $error)) {
            return $this->{$error}();
        } 
    }

    public function error_931()
    {
        $this->notifications->create($user, [
            'icon' => 'fa-users',
            'body' => 'Test',
            'action_text' => 'Test Button',
            'action_url' => '/test',
        ]);
    }
}

MyCustomController.php

<?php

namespace App\Http\Controllers;

use App\ResponseErrorHandler;

class MyCustomController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
    // Triggering with hard coded error to test
        (new ResponseErrorHandler)->error_931;
     }
}

When I visit the route that fires the index method in my controller I get the following FatalThrowableError:

Type error: Too few arguments to function App\ResponseErrorHandler::__construct(), 0 passed

How do I fix this? Any help is appreciated!

3rd June, 2017

clat23 started a new conversation Handling Errors From An Outside API • 2 months ago

I have a model that sends requests to an outside API. When this outside API is unable to process the request, it responds with a failure along with an error code and an error message.

My model checks the response for these failures and then throws an exception with a generic message. My controller then catches this exception and flashes that generic message to the user.

I would like to handle each failure depending on the error code that is returned. (i.e. if the app receives error code "12345" then the app flashes "This sample error message" to the user. If the app receives error code "54321", then the app redirects to a specific view).

The most basic way I have in mind to accomplish this is to use a switch statement and write the logic depending on the "case" (error code). However, this outside API has hundreds of different types of error codes, so this can make my model messy really quick.

So my next thought was to create a helper class or a helper function to remove all of this logic from my model. But is this really the cleanest way to do it?

What is the right way to handle this? Does Laravel offer anything for this situation? Any help is appreciated...

16th May, 2017

clat23 left a reply on LengthAwarePaginator Could Not Be Converted To Int • 3 months ago

No data in the browser. I get an empty table. I will try some other things. Thank you for trying to help me @jlrdw

clat23 left a reply on LengthAwarePaginator Could Not Be Converted To Int • 3 months ago

This:

public function getProcessed() {
        $processedSales = Sale::where('user_id', Auth::user()->id)
            ->where('processed', '=', 1)
            ->orderBy('sale_date', 'desc')
            ->paginate(1);
            Var_dump($processedSales);

Gets me this:

LengthAwarePaginator {#405 ▼
  #total: 2
  #lastPage: 2
  #items: Collection {#404 ▼
    #items: array:1 [▼
      0 => Sale {#401 ▶}
    ]
  }
  #perPage: 1
  #currentPage: 1
  #path: "http://myapp.app/sales"
  #query: []
  #fragment: null
  #pageName: "page"
}

clat23 left a reply on LengthAwarePaginator Could Not Be Converted To Int • 3 months ago

Removed:

foreach ($processedSales as $sale) {
            $sale->sale_date = Timezone::convertFromUTC($sale->sale_date, Auth::user()->timezone);
        }

Still no results.... this is so strange.

clat23 left a reply on LengthAwarePaginator Could Not Be Converted To Int • 3 months ago

@jimmy0699 I tried

@foreach ($processedSales as $sale)
{{{ var_dump($sale) }}}
@endforeach 

I'm still getting an empty table.

I tried

{{ dd($sale) }}

Also results in an empty table.

clat23 left a reply on LengthAwarePaginator Could Not Be Converted To Int • 3 months ago

@jlrdw

$sale['quantity_sold']

Still gives me an empty result

$unprocessedSales was a mistake. I changed it to $processedSales. Same result....which is not a problem anymore. Now I'm having issues accessing the items in the collection.

clat23 left a reply on LengthAwarePaginator Could Not Be Converted To Int • 3 months ago

Ok we're getting somewhere. I replaced @if ($processedSales > 0) with @if (!empty($unprocessedSales)) and it got rid of the error. But now my table is empty.

I think now the problem lies in @foreach ($processedSales as $sale). I tried replacing it with @foreach ($processedSales->items as $sale) but I get this error:

Cannot access protected property Illuminate\Pagination\LengthAwarePaginator::$items

How do I access 'items' in:

LengthAwarePaginator {#401 ▼
  #total: 4
  #lastPage: 4
  #items: Collection {#405 ▼
    #items: array:1 [▼
      0 => Sale {#406 ▼

clat23 left a reply on LengthAwarePaginator Could Not Be Converted To Int • 3 months ago

I tried removing @if ($processedSales > 0) from the view (and the corresponding @endif) and it works. So I'm not sure why @if ($processedSales > 0) causes the error:

Object of class Illuminate\Pagination\LengthAwarePaginator could not be converted to int (View: /home/vagrant/Code/myapp/resources/views/sales/index.blade.php)

clat23 left a reply on LengthAwarePaginator Could Not Be Converted To Int • 3 months ago

It's Laravel's paginator that's integrated with the query builder and Eloquent ORM.

https://laravel.com/docs/5.4/pagination#basic-usage

clat23 left a reply on LengthAwarePaginator Could Not Be Converted To Int • 3 months ago

Yes. When I add {{ dd($processedSales) }} to the view I get this:

LengthAwarePaginator {#401 ▼ #total: 4 #lastPage: 4 #items: Collection {#405 ▼ #items: array:1 [▼ 0 => Sale {#406 ▼ #dates: array:3 [▶] #connection: "mysql" #table: null #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] #perPage: 15 +exists: true +wasRecentlyCreated: false #attributes: array:27 [▶] #original: array:27 [▶] #casts: [] #dateFormat: null #appends: [] #events: [] #observables: [] #relations: [] #touches: [] +timestamps: true #hidden: [] #visible: [] #fillable: [] #guarded: array:1 [▶] } ] } #perPage: 1 #currentPage: 1 #path: "http://myapp.app/sales" #query: [] #fragment: null #pageName: "page"

clat23 left a reply on LengthAwarePaginator Could Not Be Converted To Int • 3 months ago

@jlrdw First off, thanks for the response! But I moved it to the controller just as you suggested and I still have the same error.

SalesController.php:

<?php

namespace App\Http\Controllers;

use App\Sale;
use Illuminate\Http\Request;

class SalesController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');

        // $this->middleware('subscribed');
    }

    public function index()
    {
        // Retrieve processed sales
        $processedSales = (new Sale)->paginate(1);

        return view('/sales/index')->with([
          'processedSales' => $processedSales
        ]);
    }

On a separate note, I also have a ListingsController.php and a model Listing.php. I have the paginate method in the model and it works just fine, no errors.

clat23 started a new conversation LengthAwarePaginator Could Not Be Converted To Int • 3 months ago

Here's the full error:

Object of class Illuminate\Pagination\LengthAwarePaginator could not be converted to int (View: /home/vagrant/Code/myapp/resources/views/sales/index.blade.php)

SalesController.php:

<?php

namespace App\Http\Controllers;

use App\Sale;
use Illuminate\Http\Request;

class SalesController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');

        // $this->middleware('subscribed');
    }

    public function index()
    {
        // Retrieve processed sales
        $processedSales = (new Sale)->getProcessed();

        return view('/sales/index')->with([
          'processedSales' => $processedSales
        ]);
    }

Sale.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Auth;
use Camroncade\Timezone\Facades\Timezone;

class Sale extends Model
{
    /**
     * The attributes that should be mutated to dates (Carbon instance).
     *
     * @var array
     */
    protected $dates = [
        'created_at',
        'updated_at',
        'sale_date'
    ];

    public function source()
    {
        return $this->belongsTo(Source::class);
    }

    public function getProcessed() {
        $processedSales = Sale::where('user_id', Auth::user()->id)
            ->where('processed', '=', 1)
            ->orderBy('sale_date', 'desc')
            ->paginate(1);

        foreach ($processedSales as $sale) {
            $sale->sale_date = Timezone::convertFromUTC(
        $sale->sale_date, Auth::user()->timezone);
        }

        return $processedSales;
    }

resources/views/sales/index.blade.php

@extends('spark::layouts.app')

@section('content')
<home :user="user" inline-template>
    <!-- Application Dashboard -->
    <div class="row">
        <div class="col-md-12">
            <!-- Processed Sales Table -->
            <div class="panel panel-default">
                <div class="panel-heading">Processed Sales</div>
                <div class="panel-body">
                    @if ($processedSales > 0)
                        <div class="table-responsive">
                            <table class="table table-condensed">
                                <thead>
                                    <tr>
                                        <th>Sale Date</th>
                                        <th class="text-center">Quantity</th>
                                        <th class="text-center">Sale Price</th>
                                        <th class="text-center">Item Cost</th>
                                        <th class="text-center">Profit</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach ($processedSales as $sale)
                                        <tr>
                                            <td>{{ $sale->sale_date->format('m-d-Y') }}</td>
                                            <td class="text-center">{{ $sale->quantity_sold }}</td>
                                            <td class="text-center">{{ $sale->sale_price }}</td>
                                            <td class="text-center text-danger">({{ $sale->seller_cost }})</td>
                                            @if (strpos($sale->profit, '-') !== false)
                                                <td class="text-danger text-center">
                            <strong>({{ $sale->profit }})</strong>
                        </td>
                                            @else
                                                <td class="text-success text-center">
                            <strong>{{ $sale->profit }}</strong>
                        </td>
                                            @endif
                                            <td>
                                                <span 
                            class="glyphicon glyphicon-list-alt" 
                            data-toggle="modal" 
                            data-target="#saleInfo-{{ $sale->order_id }}">              
                        </span>&nbsp;&nbsp;
                                                <span 
                            class="glyphicon glyphicon-trash" 
                            data-toggle="modal" 
                            data-target="#confirmDelete-{{ $sale->id }}">
                        </span>
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                        {{ $processedSales->links() }}
                        @foreach ($processedSales as $sale)
                            @if ($sale->processed)
                                <div id="saleInfo-{{ $sale->order_id }}" class="modal fade" role="dialog">
                                    <div class="modal-dialog">
                                        <!-- Modal content-->
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <button 
                            type="button" 
                            class="close" 
                            data-dismiss="modal">&times;
                        </button>
                                                <h4 class="modal-title">Detailed Sale Information</h4>
                                            </div>
                                            <div class="modal-body">
                                                <p><strong>Date of Sale: </strong>
                            {{ $sale->sale_date->format('m-d-Y') }}<br>
                                                <strong>Sale Price: </strong>{{ $sale->sale_price }}<br>
                                                <strong>Quantity Sold: </strong>{{ $sale->quantity_sold }}<br>
                                                <strong>Your Cost: </strong>{{ $sale->seller_cost }}<br>
                                                <strong>Your Net Profit: </strong>{{ $sale->profit }}<br>
                                                <strong>Buyer Name: </strong>{{ $sale->buyer_name }}<br>
                                                <strong>Buyer E-Mail: </strong>{{ $sale->buyer_email }}</p><br>
                                            </div>
                                            <div class="modal-footer">
                                                <button 
                            type="button" 
                            class="btn btn-default" 
                            data-dismiss="modal">Close
                        </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div id="confirmDelete-{{ $sale->id }}" class="modal fade" role="dialog">
                                    <div class="modal-dialog modal-sm">
                                        <!-- Modal content-->
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <button 
                            type="button" 
                            class="close" 
                            data-dismiss="modal">&times;
                        </button>
                                                <h4 class="modal-title">Delete Confirmation</h4>
                                            </div>
                                            <div class="modal-body">
                                                <p>
                            <strong>Are you sure you want to delete this sale?</strong>
                        </p>
                                            </div>
                                            <div class="modal-footer">
                                                <form method="POST" action="/sales/{{ $sale->id }}">
                                                    {{ method_field('DELETE') }}
                                                    {{ csrf_field() }}
                                                    <button 
                                type="submit" 
                                class="btn btn-primary">Delete
                            </button>
                                                    <button 
                                type="button" 
                                class="btn btn-default" 
                                data-dismiss="modal">Cancel
                            </button>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            @endif
                        @endforeach
                    @else
                        <p>There are no processed sales at this time.</p>
                    @endif
                </div>
            </div>
        </div>
    </div>
</home>
@endsection

What's causing the error? Any help would be appreciated!

29th April, 2017

clat23 started a new conversation Custom Exceptions: Technical Message For Logs Vs General Message For Users • 3 months ago

See the following code:

        if (!isset($response->Ack) || $response->Ack == 'Failure'){
            session(['response' => $response->asXML()]);
            throw new ReviseItemException('There was a problem updating the price for this item.');
        }

$response is what an API returns whether successful with data I am requesting, or technical error codes and messages from the API.

I save it to a session so that I can log the technical API response. I throw a ReviseItemException with a general message for the user so that it is understandable for the user.

This all works great, no problems.

My question is: how do I get the technical API response from a scheduled artisan command for logging purposes? When a ReviseItemException is thrown, the $response variable is no longer available to the scheduled artisan command.

One option is to output $response to the ReviseItemException message, but the problem with this is that the user will not get a generic understandable message.

Any help would be appreciated!

25th April, 2017

clat23 left a reply on "[ReflectionException] Class App\SourceUpdater Does Not Exist" • 3 months ago

@edoc Thank you, I feel so stupid for missing that. Although, I'm new to all this, so namespacing is not second to nature yet.

Also should mention that I was missing () from $this->source->update; in order for the above code to work properly.

clat23 started a new conversation "[ReflectionException] Class App\SourceUpdater Does Not Exist" • 3 months ago

Followed the documentation: https://laravel.com/docs/5.4/artisan#writing-commands

app/console/commands/UpdateSource.php:

<?php

namespace App\Console\Commands;

use App\SourceUpdater;
use Illuminate\Console\Command;

class UpdateSource extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'dsa:update-source';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update source item information (i.e. price, availability, etc)';

    /**
    * The source update service
    *
    * @var SourceUpdater
    */
    protected $source;

    /**
     * Create a new command instance.
     *
     * @param  SourceUpdater  $source
     * @return void
     */
    public function __construct(SourceUpdater $source)
    {
        parent::__construct();

        $this->source = $source;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->source->update;
    }
}

app/SourceUpdater.php:

<?php

use App\Source;

class SourceUpdater {

    public function update()
    {
        $source = Source::find(1);
        $source->price = 79;
        $source->save();
    }

}

app/console/Kernel.php:

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\UpdateSource::class
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')
        //          ->hourly();
    }

    /**
     * Register the Closure based commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        require base_path('routes/console.php');
    }
}

I get the error "[ReflectionException] Class App\SourceUpdater does not exist" when I run "php artisan list" or "php artisan dsa:update-source".

I've tried composer update then composer dump-autoload.

I get this in the console when I run composer update:

Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 0 installs, 0 updates, 0 removals
Generating autoload files
> Illuminate\Foundation\ComposerScripts::postUpdate
> php artisan optimize


  [ReflectionException]
  Class App\SourceUpdater does not exist


Script php artisan optimize handling the post-update-cmd event returned with error code 1

Any help would be appreciated

22nd April, 2017

clat23 started a new conversation Should I Schedule A Custom Artisan Command To Accomplish This? • 3 months ago

I have a database that I want to update every hour from an outside source (through the use of their API). I'm thinking of creating an artisan command with logic to retrieve information via the API and update into my database. Then use the scheduler in Laravel to trigger this custom artisan command every hour. Is this the right way to do this? Is there a better way? Any help in pointing me in the right direction is appreciated...

21st March, 2017

clat23 left a reply on Bootstrap Styling Looks Different With Laravel Spark? • 4 months ago

@douglas_quaid I followed Gorby's suggestion of editing the styles in app.css

I googled "twitter bootstrap colors" for hex codes to get the correct color codes.

1st March, 2017

clat23 left a reply on Routing To A Controller Within A Route Function • 5 months ago

Thanks @Snapey !

clat23 left a reply on Routing To A Controller Within A Route Function • 5 months ago

Thanks @Cronix I had the logic in my [email protected] but I felt it was getting very messy so I thought I'd separate it. I think I'll go with putting it in a middleware.

clat23 started a new conversation Routing To A Controller Within A Route Function • 5 months ago

I want to route to a view if a user's api token is expired and route to a controller if it's not. Here's my routes.php

Route::get('/sales/pending', function () {
    $now = Carbon::now();
    $expiration = Carbon::createFromFormat('Y-m-d H:i:s', Auth::user()->api_token_expiration);
    $expired = ($now->gt($expiration));
    if($expired == true){
        return view('/sales/token-expired');
    } else {
        return controller([email protected]'); //This is what's giving me an error
    }
});

First of all, is this the best place to have this kind of logic? If so, how do I have the routes file point to the [email protected] controller when the user's token is expired?

clat23 left a reply on Bootstrap Styling Looks Different With Laravel Spark? • 5 months ago

Well, I took my non-Spark Laravel app.css and overwrote the app.css in Laravel Spark and the result was no styling whatsoever. So there goes that idea. I also looked at my non-Spark app.css and the styling for the .thumbnail background was also gray there too and same problems with the btn-warning. So is Laravel Spark not entirely pulling from app.css?

clat23 left a reply on Bootstrap Styling Looks Different With Laravel Spark? • 5 months ago

I found the .thumbnail and btn-warning styling in app.css and changing them worked. But now, it makes me wonder what else is off. Would it be safe to take the app.css from my non-Spark install of Laravel and overwrite my Laravel Spark's app.css?

Also what do you mean by "my template css"? Is this your app.css? And what do you mean by "Spark default"? Is this Spark's version of app.css?

28th February, 2017

clat23 started a new conversation Bootstrap Styling Looks Different With Laravel Spark? • 5 months ago

I recoded my app from a Laravel 5 installation to a new Laravel Spark installation. However I noticed that some of the bootstrap styling is off.

Take for example a bootstrap thumnail:

<div class="row">
  <div class="col-sm-6 col-md-4">
    <div class="thumbnail">
      <img src="..." alt="...">
      <div class="caption">
        <h3>Thumbnail label</h3>
        <p>...</p>
        <p><a href="#" class="btn btn-warning" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
      </div>
    </div>
  </div>
</div>

In my Laravel 5 installation the thumbnail background is white. But in the Laravel Spark installation, the thumbnail background is gray.

Furthermore, the btn-warning button is yellow/green when it's supposed to be orange. There's no problems with the other buttons such as btn-primary and btn-success --- these buttons have blue and green styling respectively.

Does anyone know what is causing this?

21st February, 2017

clat23 started a new conversation What Is The Purpose Of Handler.php? • 5 months ago

I have read the following documentation:

https://laravel.com/docs/5.4/errors#the-exception-handler

However, it doesn't go into detail on when the exception handler is used. Currently I am creating custom exceptions in App/Exceptions then I Use App/Exceptions/CustomException in my controller that has try/catch blocks.

Here's some sample code:

SomeController.php:

use App\Exceptions\CantDoException;
                          //use App\Exceptions\Handler;

                          function doSomething()
                          {
                              throw new CantDoException('Unable to do that something');
                          }

                          try {
                              doSomething();
                          }
                          catch(CantDoException $e)
                          {
                              print $e->getMessage();
                          }

App/Exceptions/CantDoException.php:

<?php

namespace App\Exceptions;
use Exception;

class CantDoException extends Exception {}

The above sample code works just fine for me. So what's the point of using the Exception Handler in Handler.php?

19th February, 2017

clat23 left a reply on ReflectionException In RouteSignatureParameters.php • 5 months ago

Figured it out. Turns out it was just a stupid syntax mistake on my part. There's a missing array closure bracket at the end of SetTimezone.php

clat23 left a reply on ReflectionException In RouteSignatureParameters.php • 5 months ago

It might be worth mentioning that I am using Laravel Spark. I know there are some differences there, but I have checked and double checked. This has really stumped me. Anyone have any idea on what I'm doing wrong?

18th February, 2017

clat23 left a reply on ReflectionException In RouteSignatureParameters.php • 5 months ago

Sorry. Here you go, SetTimezone.php:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class SetTimezone extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'timezone' => [
                'required',
                Rule::in([
                    'Pacific/Midway',
                    'Pacific/Samoa',
                    'Pacific/Honolulu',
                    'US/Alaska',
                    'America/Los_Angeles',
                    'America/Tijuana',
                    'US/Arizona',
                    'America/Chihuahua',
                    'America/Chihuahua',
                    'America/Mazatlan',
                    'US/Mountain',
                    'America/Managua',
                    'US/Central',
                    'America/Mexico_City',
                    'America/Mexico_City',
                    'America/Monterrey',
                    'Canada/Saskatchewan',
                    'America/Bogota',
                    'US/Eastern',
                    'US/East-Indiana',
                    'America/Lima',
                    'America/Bogota',
                    'Canada/Atlantic',
                    'America/Caracas',
                    'America/La_Paz',
                    'America/Santiago',
                    'Canada/Newfoundland',
                    'America/Sao_Paulo',
                    'America/Argentina/Buenos_Aires',
                    'America/Argentina/Buenos_Aires',
                    'America/Godthab',
                    'America/Noronha',
                    'Atlantic/Azores',
                    'Atlantic/Cape_Verde',
                    'Africa/Casablanca',
                    'Europe/London',
                    'Etc/Greenwich',
                    'Europe/Lisbon',
                    'Europe/London',
                    'Africa/Monrovia',
                    'UTC',
                    'Europe/Amsterdam',
                    'Europe/Belgrade',
                    'Europe/Berlin',
                    'Europe/Berlin',
                    'Europe/Bratislava',
                    'Europe/Brussels',
                    'Europe/Budapest',
                    'Europe/Copenhagen',
                    'Europe/Ljubljana',
                    'Europe/Madrid',
                    'Europe/Paris',
                    'Europe/Prague',
                    'Europe/Rome',
                    'Europe/Sarajevo',
                    'Europe/Skopje',
                    'Europe/Stockholm',
                    'Europe/Vienna',
                    'Europe/Warsaw',
                    'Africa/Lagos',
                    'Europe/Zagreb',
                    'Europe/Athens',
                    'Europe/Bucharest',
                    'Africa/Cairo',
                    'Africa/Harare',
                    'Europe/Helsinki',
                    'Europe/Istanbul',
                    'Asia/Jerusalem',
                    'Europe/Helsinki',
                    'Africa/Johannesburg',
                    'Europe/Riga',
                    'Europe/Sofia',
                    'Europe/Tallinn',
                    'Europe/Vilnius',
                    'Asia/Baghdad',
                    'Asia/Kuwait',
                    'Europe/Minsk',
                    'Africa/Nairobi',
                    'Asia/Riyadh',
                    'Europe/Volgograd',
                    'Asia/Tehran',
                    'Asia/Muscat',
                    'Asia/Baku',
                    'Europe/Moscow',
                    'Asia/Muscat',
                    'Europe/Moscow',
                    'Asia/Tbilisi',
                    'Asia/Yerevan',
                    'Asia/Kabul',
                    'Asia/Karachi',
                    'Asia/Karachi',
                    'Asia/Tashkent',
                    'Asia/Calcutta',
                    'Asia/Kolkata',
                    'Asia/Calcutta',
                    'Asia/Calcutta',
                    'Asia/Calcutta',
                    'Asia/Katmandu',
                    'Asia/Almaty',
                    'Asia/Dhaka',
                    'Asia/Dhaka',
                    'Asia/Yekaterinburg',
                    'Asia/Rangoon',
                    'Asia/Bangkok',
                    'Asia/Bangkok',
                    'Asia/Jakarta',
                    'Asia/Novosibirsk',
                    'Asia/Hong_Kong',
                    'Asia/Chongqing',
                    'Asia/Hong_Kong',
                    'Asia/Krasnoyarsk',
                    'Asia/Kuala_Lumpur',
                    'Australia/Perth',
                    'Asia/Singapore',
                    'Asia/Taipei',
                    'Asia/Ulan_Bator',
                    'Asia/Urumqi',
                    'Asia/Irkutsk',
                    'Asia/Tokyo',
                    'Asia/Tokyo',
                    'Asia/Seoul',
                    'Asia/Tokyo',
                    'Australia/Adelaide',
                    'Australia/Darwin',
                    'Australia/Brisbane',
                    'Australia/Canberra',
                    'Pacific/Guam',
                    'Australia/Hobart',
                    'Australia/Melbourne',
                    'Pacific/Port_Moresby',
                    'Australia/Sydney',
                    'Asia/Yakutsk',
                    'Asia/Vladivostok',
                    'Pacific/Auckland',
                    'Pacific/Fiji',
                    'Pacific/Kwajalein',
                    'Asia/Kamchatka',
                    'Asia/Magadan',
                    'Pacific/Fiji',
                    'Asia/Magadan',
                    'Asia/Magadan',
                    'Pacific/Auckland',
                    'Pacific/Tongatapu'
                ])
        ];
    }
}

clat23 started a new conversation ReflectionException In RouteSignatureParameters.php • 5 months ago

I have created a new form request using php artisan make:request SetTimezone. I have followed the Laravel 5.4 documentation (https://laravel.com/docs/5.4/validation#creating-form-requests). However, I am getting this:

ReflectionException in RouteSignatureParameters.php line 25: Class app\Http\Requests\SetTimezone does not exist

Here's my SettingsController.php (end truncated):

<?php

namespace App\Http\Controllers;

// use Illuminate\Http\Request;
use Auth;
use App\Ebay;
use App\Paypal;
use Carbon\Carbon;
use Camroncade\Timezone\Facades\Timezone;
use App\Http\Requests\SetTimezone;

class SettingsController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');

        // $this->middleware('subscribed');
    }

    public function show()
    {
        Auth::user()->updateTokenStatus();
        return view('settings', Auth::user());
    }

    public function setTimezone(SetTimezone $request)
    {
        $newTimezone = request()->timezone;
        Auth::user()->setTimezone($newTimezone);
        return redirect()->action([email protected]');
    }

And here's my SetTimezone.php (created by php artisan make:request command) (also truncated):

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class SetTimezone extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'timezone' => [
                'required',
                Rule::in([
                    'Pacific/Midway',
                    'Pacific/Samoa',
                    'Pacific/Honolulu',
                    'US/Alaska',
                    'America/Los_Angeles',
                    'America/Tijuana',
                    'US/Arizona',
                    'America/Chihuahua',
                    'America/Chihuahua',
                    'America/Mazatlan',
                    'US/Mountain',
                    'America/Managua',
                    'US/Central',

Why is it not finding SetTimezone from App\Http\Requests? I am looking at the folder structure and clearly I have a SetTimezone.php in the App/Http/Requests folder. Any help would be appreciated. Thanks!

17th February, 2017

clat23 left a reply on Form Request Validation, Class App\Http\Controllers\StoreBlogPost Does Not Exist • 5 months ago

I have the same problem and applied the solution of the best answer but I'm still getting the error:

ReflectionException in RouteSignatureParameters.php line 25: Class App\Http\Requests\SetTimezone does not exist

Here's my SettingsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use App\Ebay;
use App\Paypal;
use Carbon\Carbon;
use Camroncade\Timezone\Facades\Timezone;
use App\Http\Requests\SetTimezone;


class SettingsController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');

        // $this->middleware('subscribed');
    }

    public function show()
    {
        Auth::user()->updateTokenStatus();
        return view('settings', Auth::user());
    }

    public function setTimezone(SetTimezone $request)
    {
        $newTimezone = request()->timezone;
        Auth::user()->setTimezone($newTimezone);
        return redirect()->action([email protected]');
    }

and my SetTimezone.php that was created from "php artisan make:request SetTimezone"

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class SetTimezone extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'timezone' => [
                'required',
                Rule::in([
                    'Pacific/Midway',
                    'Pacific/Samoa',
                    'Pacific/Honolulu',
                    'US/Alaska',
                    'America/Los_Angeles',
                    'America/Tijuana',
                    'US/Arizona',
                    'America/Chihuahua',
                    'America/Chihuahua',
                    'America/Mazatlan',
                    'US/Mountain',
                    'America/Managua',
                    'US/Central',
                    'America/Mexico_City',
                    'America/Mexico_City',
                    'America/Monterrey',
                    'Canada/Saskatchewan',
                    'America/Bogota',
                    'US/Eastern',
                    'US/East-Indiana',
                    'America/Lima',
                    'America/Bogota',
                    'Canada/Atlantic',
                    'America/Caracas',
                    'America/La_Paz',
                    'America/Santiago',
                    'Canada/Newfoundland',
                    'America/Sao_Paulo',
                    'America/Argentina/Buenos_Aires',
                    'America/Argentina/Buenos_Aires',
                    'America/Godthab',
                    'America/Noronha',
                    'Atlantic/Azores',
                    'Atlantic/Cape_Verde',
                    'Africa/Casablanca',
                    'Europe/London',
                    'Etc/Greenwich',
                    'Europe/Lisbon',
                    'Europe/London',
                    'Africa/Monrovia',
                    'UTC',
                    'Europe/Amsterdam',
                    'Europe/Belgrade',
                    'Europe/Berlin',
                    'Europe/Berlin',
                    'Europe/Bratislava',
                    'Europe/Brussels',
                    'Europe/Budapest',
                    'Europe/Copenhagen',
                    'Europe/Ljubljana',
                    'Europe/Madrid',
                    'Europe/Paris',
                    'Europe/Prague',
                    'Europe/Rome',
                    'Europe/Sarajevo',
                    'Europe/Skopje',
                    'Europe/Stockholm',
                    'Europe/Vienna',
                    'Europe/Warsaw',
                    'Africa/Lagos',
                    'Europe/Zagreb',
                    'Europe/Athens',
                    'Europe/Bucharest',
                    'Africa/Cairo',
                    'Africa/Harare',
                    'Europe/Helsinki',
                    'Europe/Istanbul',
                    'Asia/Jerusalem',
                    'Europe/Helsinki',
                    'Africa/Johannesburg',
                    'Europe/Riga',
                    'Europe/Sofia',
                    'Europe/Tallinn',
                    'Europe/Vilnius',
                    'Asia/Baghdad',
                    'Asia/Kuwait',
                    'Europe/Minsk',
                    'Africa/Nairobi',
                    'Asia/Riyadh',
                    'Europe/Volgograd',
                    'Asia/Tehran',
                    'Asia/Muscat',
                    'Asia/Baku',
                    'Europe/Moscow',
                    'Asia/Muscat',
                    'Europe/Moscow',
                    'Asia/Tbilisi',
                    'Asia/Yerevan',
                    'Asia/Kabul',
                    'Asia/Karachi',
                    'Asia/Karachi',
                    'Asia/Tashkent',
                    'Asia/Calcutta',
                    'Asia/Kolkata',
                    'Asia/Calcutta',
                    'Asia/Calcutta',
                    'Asia/Calcutta',
                    'Asia/Katmandu',
                    'Asia/Almaty',
                    'Asia/Dhaka',
                    'Asia/Dhaka',
                    'Asia/Yekaterinburg',
                    'Asia/Rangoon',
                    'Asia/Bangkok',
                    'Asia/Bangkok',
                    'Asia/Jakarta',
                    'Asia/Novosibirsk',
                    'Asia/Hong_Kong',
                    'Asia/Chongqing',
                    'Asia/Hong_Kong',
                    'Asia/Krasnoyarsk',
                    'Asia/Kuala_Lumpur',
                    'Australia/Perth',
                    'Asia/Singapore',
                    'Asia/Taipei',
                    'Asia/Ulan_Bator',
                    'Asia/Urumqi',
                    'Asia/Irkutsk',
                    'Asia/Tokyo',
                    'Asia/Tokyo',
                    'Asia/Seoul',
                    'Asia/Tokyo',
                    'Australia/Adelaide',
                    'Australia/Darwin',
                    'Australia/Brisbane',
                    'Australia/Canberra',
                    'Pacific/Guam',
                    'Australia/Hobart',
                    'Australia/Melbourne',
                    'Pacific/Port_Moresby',
                    'Australia/Sydney',
                    'Asia/Yakutsk',
                    'Asia/Vladivostok',
                    'Pacific/Auckland',
                    'Pacific/Fiji',
                    'Pacific/Kwajalein',
                    'Asia/Kamchatka',
                    'Asia/Magadan',
                    'Pacific/Fiji',
                    'Asia/Magadan',
                    'Asia/Magadan',
                    'Pacific/Auckland',
                    'Pacific/Tongatapu'
                ])
        ];
    }
}

3rd February, 2017

clat23 left a reply on Registration: "Something Went Wrong. Please Try Again Or Contact Customer Support." • 6 months ago

Ok so I added

Use Carbon\Carbon;

to SparkServiceProvider.php and it worked. Does the Spark Documentation need to be updated?

Does the Laravel Spark Framework need to be updated to have this on fresh install?

clat23 left a reply on Registration: "Something Went Wrong. Please Try Again Or Contact Customer Support." • 6 months ago

Here's the error thrown in larvel.log:

[2017-02-04 03:45:48] local.ERROR: Symfony\Component\Debug\Exception\FatalThrowableError: Class 'App\Providers\Carbon' not found in /home/vagrant/Code/myapp/app/Providers/SparkServiceProvider.php:85

clat23 left a reply on Registration: "Something Went Wrong. Please Try Again Or Contact Customer Support." • 6 months ago

It's also worth noting that when I remove from SparkServiceProviders.php the following code;

Spark::createUsersWith(function ($request) {
          $user = Spark::user();
          $data = $request->all();
          $user->forceFill([
              'name' => $data['name'],
              'email' => $data['email'],
              'timezone' => $data['timezone'],
              'password' => bcrypt($data['password']),
              'last_read_announcements_at' => Carbon::now(),
              'trial_ends_at' => Carbon::now()->addDays(Spark::trialDays()),
          ])->save();
          return $user;
        });

No error on user registration. But the user does not receive the timezone in the user's table in the database.

clat23 started a new conversation Registration: "Something Went Wrong. Please Try Again Or Contact Customer Support." • 6 months ago

I have followed this documentation: https://spark.laravel.com/docs/3.0/adding-registration-fields

Here's my code:

register-common-form.blade.php:

    <!-- Timezone -->
    <?php require(app_path().'/Includes/timezones.php'); ?>
    <div class="form-group" :class="{'has-error': registerForm.errors.has('timezone')}">
        <label class="col-md-4 control-label">Timezone</label>

        <div class="col-md-6">
            <select class="form-control" name="timezone" v-model="registerForm.timezone">
            @foreach ($timezones as $formTimezone => $utc)
                <option value="{{ $formTimezone }}">{{ $utc }}</option>
            @endforeach
            </select>

            <span class="help-block" v-show="registerForm.errors.has('timezone')">
                @{{ registerForm.errors.get('timezone') }}
            </span>
        </div>
    </div>

app.js


/*
 |--------------------------------------------------------------------------
 | Laravel Spark Bootstrap
 |--------------------------------------------------------------------------
 |
 | First, we will load all of the "core" dependencies for Spark which are
 | libraries such as Vue and jQuery. This also loads the Spark helpers
 | for things such as HTTP calls, forms, and form validation errors.
 |
 | Next, we'll create the root Vue application for Spark. This will start
 | the entire application and attach it to the DOM. Of course, you may
 | customize this script as you desire and load your own components.
 |
 */

require('spark-bootstrap');

require('./components/bootstrap');

Spark.forms.register = {
    timezone: ''
};

var app = new Vue({
    mixins: [require('spark')]
});

SparkServiceProvider.php

<?php

namespace App\Providers;

use Laravel\Spark\Spark;
use Laravel\Spark\Providers\AppServiceProvider as ServiceProvider;

class SparkServiceProvider extends ServiceProvider
{
    /**
     * Your application and company details.
     *
     * @var array
     */
    protected $details = [
        'vendor' => 'Your Company',
        'product' => 'Your Product',
        'street' => 'PO Box 111',
        'location' => 'Your Town, NY 12345',
        'phone' => '555-555-5555',
    ];

    /**
     * The address where customer support e-mails should be sent.
     *
     * @var string
     */
    protected $sendSupportEmailsTo = null;

    /**
     * All of the application developer e-mail addresses.
     *
     * @var array
     */
    protected $developers = [
        //
    ];

    /**
     * Indicates if the application will expose an API.
     *
     * @var bool
     */
    protected $usesApi = true;

    /**
     * Finish configuring Spark for the application.
     *
     * @return void
     */
    public function booted()
    {
        Spark::useStripe()->noCardUpFront()->trialDays(10);

        Spark::freePlan()
            ->features([
                'First', 'Second', 'Third'
            ]);

        Spark::plan('Basic', 'myapp-test-1')
            ->price(10)
            ->features([
                'First', 'Second', 'Third'
            ]);

        Spark::validateUsersWith(function () {
            return [
                'name' => 'required|max:255',
                'email' => 'required|email|max:255|unique:users',
                'timezone' => 'required|max:50',
                'password' => 'required|confirmed|min:6',
                'vat_id' => 'max:50|vat_id',
                'terms' => 'required|accepted',
            ];
        });

        Spark::createUsersWith(function ($request) {
          $user = Spark::user();
          $data = $request->all();
          $user->forceFill([
              'name' => $data['name'],
              'email' => $data['email'],
              'timezone' => $data['timezone'],
              'password' => bcrypt($data['password']),
              'last_read_announcements_at' => Carbon::now(),
              'trial_ends_at' => Carbon::now()->addDays(Spark::trialDays()),
          ])->save();
          return $user;
        });
    }
}

I have added

$table->string('timezone')->nullable();

to my create_users_table migration

I have updated my Users.php model to add timezone:

    protected $fillable = [
        'name',
        'email',
        'timezone',
    ];

When I attempt to register a new user with my app, I get the following error: "Something went wrong. Please try again or contact customer support."

What did I miss?

clat23 left a reply on Should I Not Be Using Public Static Function In My Model? • 6 months ago

Point taken @patoui However, I am trying not to modify the user model. I am actually using Laravel Spark and when I attempted to add settings columns (i.e. user timezone) to the create_users_table migration, it broke the authentication process. The framework was throwing an error and was redirecting the user (me) to the registration page with an error something along the lines of "Something went wrong, contact the site administrator".

So my workaround was to break user settings off on its own model, controller and table which references the user's id on the user table.

So I guess now I have to decide whether to figure out why I am not able to add settings columns to the user table, or continue with settings as its own model, controller and table while avoiding public static functions. Any suggestions?

clat23 started a new conversation Should I Not Be Using Public Static Function In My Model? • 6 months ago

Here's my SettingsController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Setting;

class SettingsController extends Controller
{
    public function setTimezone ()
    {
        $newTimezone = request()->timezone;
        Setting::setTimezone($newTimezone);
    }
}

And here's my model Setting.php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Auth;

class Setting extends Model
{
    protected $userSettings;

    public static function setTimezone ($newTimezone)
    {
        $userSettings = static::where('user_id',  Auth::user()->id)->first();
        $userSettings->timezone = $newTimezone;
        $userSettings->save();
    }
}

I set this up in this way based on Jeffrey Way's demonstration on Eloquent here: https://laracasts.com/series/laravel-from-scratch-2017/episodes/7

While this code works properly, I do recall that using static functions is not recommended. Should I be implementing this a different way?

31st January, 2017

clat23 left a reply on Pulling In Outside Providers (Camroncade - Timezone) • 6 months ago

Yes that worked. Thanks for your help @w1n78 !

clat23 left a reply on Pulling In Outside Providers (Camroncade - Timezone) • 6 months ago

Tried this:

$timezoneForm = (new \Camroncade\Timezone\Timezone)->selectForm($user->timezone, 'Set Time Zone', $formAttributes);

Got this:

ErrorException in f6fd7675b144e6b0466b63d9fb0082b5b039e7ca.php line 23: Undefined property: stdClass::$timezone (View: /home/vagrant/Code

A bit frustrating....any help appreciated. Thanks...

clat23 left a reply on Pulling In Outside Providers (Camroncade - Timezone) • 6 months ago

Ok, I have a little progress based on @w1n78 's recommendation. I noticed that the outside service provider is "Camroncade\Timezone\TimezoneServiceProvider::class,"

So I tried this instead:

$timezoneForm = \Camroncade\Timezone\Timezone::selectForm($user->timezone, 'Set Time Zone', $formAttributes);

And got this error instead:

ErrorException in f6fd7675b144e6b0466b63d9fb0082b5b039e7ca.php line 23: Non-static method Camroncade\Timezone\Timezone::selectForm() should not be called statically (View: /home/vagrant/Code

Any thoughts?

clat23 left a reply on Pulling In Outside Providers (Camroncade - Timezone) • 6 months ago

Thanks @w1n78, I tried your recommendation but here's the new error:

ErrorException in f6fd7675b144e6b0466b63d9fb0082b5b039e7ca.php line 23: Class 'Camroncade\Timezone' not found (View: /home/vagrant/Code

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.