ajck

ajck

Member Since 2 Years Ago

Experience Points 2,480
Experience Level 1

2,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 0
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

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

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

05 Dec
7 months ago

ajck left a reply on Upload Multiple Files To AWS S3 From Laravel?

@markll Thanks very much. Looks like what I need :) I've adapted the code slightly, listed below. Does it look right do you think? I presume your line

foreach($this->fetchFilenamesToUpload() as $keyToFile => $pathToFile) {

is just iterating through a standard array of keys and paths as key => value?

Also I was wondering how to handle errors effectively. I've just used the SDK docs examples for Promise error handling. Ideally I would like to have used the code here: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/s3-multipart-upload.html#recovering-from-errors to resume from failed uploads but that's probably over engineering in my case.

My code:

//Create a S3Client
$s3Client = new S3Client([
    'profile' => 'default',
    'region' => env('AWS_REGION'),
    'version' => 'latest'
]);
$promises = [];
// Compose promises:
foreach($filenames_array as $keyToFile => $pathToFile) {
    $uploader = new MultipartUploader($s3Client, $pathToFile, [
        'bucket'          => env('AWS_REGION'),
        'key'             => $keyToFile,
        'concurrency'     => 25,
    ]);
    $promises[] = $uploader->promise();
}
// Execute upload:
$aggregate = \GuzzleHttp\Promise\all($promises);

try {
    $result = $aggregate->wait();
} catch (S3Exception $e) {
    // Handle the error
    // echo $e->getMessage();
}

Thanks again

03 Dec
7 months ago

ajck started a new conversation Upload Multiple Files To AWS S3 From Laravel?

I'm currently using the standard Laravel file storage to upload a single file to S3 but now have a need to upload a whole load of separate files at once (possibly up to 200). I want to do this as efficiently as possible, rather than using separate requests. Is this possible somehow, either using Laravel storage, the Flysystem library it's based on or the official Amazon S3 PHP SDK? Separate files are very small, about 1Kb each.

Thanks!

31 Oct
8 months ago

ajck started a new conversation How To Modify Return View() Call To Return As JSON Encoded?

In my controllers, various functions are just doing a standard return view() call to fill a Blade template with some variables and return to the client browser. I'm now adapting our company's site to an app using PhoneGap/Cordova and going to be loading the site pages over AJAX using JSON and injecting the content directly into the app's single page (thus simulating a multi-page app).

Is there a way to easily JSON encode the view output as JSON if e.g. a variable is set in the session indicating the client is the app?

I suppose the obvious way is response()->json(output_of_view) and somehow putting the view content into that, or is there a better way? Thanks

19 Oct
9 months ago

ajck left a reply on Encrypting Model Data

@martinbean your solution to this looks great, thank you but is it possible to use it with fields that need to be searchable (i.e. appear in where clauses), or how could it be adapted to that if possible? Thanks

28 Sep
9 months ago

ajck started a new conversation How To Specify Data Field In JQuery AJAX Form Submission?

I need my HTML form data to arrive at the server via a JQuery AJAX POST request in exactly the same format as if the form had been submitted by a normal submit. I've tried using $.serialize() and $.serializeArray(), and neither gives the simple

    $('#booking-form').on('submit', function(e) {
       var formdata = $(this).serialize();
       // process data and send ajax request
       console.log(formdata);

       $.ajax({
           headers: { 'X-CSRF-TOKEN': $('#booking-form > input[name="_token"]').val() },
           type: 'POST',
           url: 'book',
           data: { data: formdata },
           success: function (data)
               {
               // Redirect to booking confirmation page:
               if(data.response == 'ok') window.location.replace(data.url);
               else alert('Card payment failed)
               },
           error: function (data) // Server error
               {
               console.log('Error:', data.responseText);
               }
           });
    
        // Prevent form submit.
        return false;
    });

Backend is Laravel (5.4) but I think this is not a Laravel-specific issue. Logging a normal form submit gives:

    array (
      'code' => '2ZSSAVGXAHMOOKGOC0SC',
      'ownername' => 'My Name',
      'housestreet' => '12 Any street, London',
      'city' => 'London',
      'ownerpcode' => 'ZipCode Here',
      'phone' => '1234567890'
    )

That's the structure I'm after. But code above gives:

    array (
      'data' => 'code=BUH1HGXDWW84SWGWSO84&ownername=My+Name&housestreet=12+Any+street%2C+London&city=London&ownerpcode=Zipcode+here&phone=1234567890')

or using $.serializeArray() gives:

    array (
      'data' => 
      array (
        0 => 
        array (
          'name' => 'code',
          'value' => 'CC22DPHQ2F40G0GCKKK0',
        ),
        2 => 
        array (
          'name' => 'ownername',
          'value' => 'My Name',
        ),
        3 => 
        array (
          'name' => 'housestreet',
          'value' => '12 Any street, London',
        ),
    etc.

How to get the data in the right format on the server over AJAX (using JQuery or plain JS)? I can't hand code the form fields into the data: parameter in the $.ajax call as some of them are dynamically generated on the server and some by JS on the front end, and include array fields for PHP to parse (e.g. form field name="item[0][extra][]")

Thanks

17 Sep
10 months ago

ajck left a reply on How To Allow Admin User To Simulate Or Authenticate As Any Other User On My Site?

My users have a type assigned to them in the DB, admin user is set as 'admin' type, they login like any other user, but then see an extra admin menu. So just trying to figure out how to allow them to edit other user's account data as if they were that user.

ajck started a new conversation How To Allow Admin User To Simulate Or Authenticate As Any Other User On My Site?

I'm trying to figure out how quickest and easiest to allow the admin user on the site I'm building to access and update any user's settings etc. E.g. I've written the code for a regular user to update their settings (and various other actions). Ideally I want an admin to be able to "be" that user as far as my code is concerned, i.e. allow the admin to do anything a user can, to that user's account. Is there any way of doing this?

If I Auth::login() as admin then from the point of view of Laravel I'm the admin user and not the user they might want to edit. If I login as the user then I don't have admin rights (which in my case means an extra admin menu on the navbar with options to suspend or delete the user, or search for other users).

Any thoughts on how to do this please, or am I overcomplicating things? I am looking for a specific functions/code to allow this, rather than a general strategy. I'm using Laravel 5.4, deployed on Heroku. I know there's middleware but it doesn't seem to do what I want as above.

Many thanks.

04 Sep
10 months ago

ajck started a new conversation How To Handle Stripe Payment Failure Via AJAX, With Standard Page Load For Success?

I've got a long and fairly complex form for a booking system that a user fills in, then pays using Stripe Checkout. I'm trying to figure out the best solution to both handle payment failure easily (so submitting form over AJAX so I don't have to try and regenerate the whole booking form with all the data the user's entered), whilst also handling payment success gracefully (so with a new page showing a booking summary and a different URL so if user clicks reload button in their browser it doesn't just take them back to the search results and booking form again)

I'm using a mixture of Laravel 5.4 and JS/JQuery to generate the booking form on the front end, and after Stripe Checkout (I'm using their standard simple integration pop up) it submits all the form + Stripe token etc back to a POST route in my Laravel backend. In my controller, I then try and charge the credit card using standard Stripe API and process the booking details into my database, and then return a Laravel view from a Blade template thus giving the user a different page and URL. As mentioned I want to switch the form submission to AJAX so payment failure can be handled easily (i.e. their big filled in form doesn't disappear, and just an alert pops up to user so they can try and enter a new card into the Stripe Checkout). That bit's fine, I'll just use this: https://stackoverflow.com/a/34099169/4059141 but then in payment succeeds I basically want the same behaviour as if I'd done a regular form POST, so the new page being displayed with a new URL.

I can generate and pass back the rendered HTML from the blade template over AJAX no problem, but that leaves the original URL in the browser's address bar, so if they hit reload on the booking summary they'll just see the search results page and blank booking form again - not what I want.

Any thoughts on a solution are welcome! Thanks

04 Aug
11 months ago

ajck left a reply on How To Debug Laravel App When No Error Info Given At All?

@jlrdw Yes, agreed - these are errors that are showing up when I deploy to Heroku though. Not sure what other information to give, the problem is there is no error information! It's a form POST request to a route in my app. I'm not looking for an answer to the particular problem, but advice on how to approach debugging when Laravel and the logs give no error information, i.e. is there some approach I can use to figure out what's going on, or am I missing error info somewhere? Thanks

ajck started a new conversation How To Debug Laravel App When No Error Info Given At All?

Hi, Deployed my Laravel 5.4 app to Heroku and a couple of times I've had the standard "Whoops, looks like something went wrong." exception page with the red banner at the top. Blank white page below that. Nothing in error logs and APP_LOG is set to errorlog and other errors and use of Log::Info() all send to stdout, i.e. Heroku's combined logs and proven to work correctly.

So, just this particular error is generating no info it seems. How to debug this? It's a post to a particular route.

Thanks.

07 Jul
1 year ago

ajck started a new conversation How To Avoid Laravel Caching Files Whilst Debugging So I Can See Changes Immediately?

I'm in the process of debugging a site and needing to make repeated small tweaks to various files, e.g. HTML, JS, blade templates, controllers etc. When I reload whatever page I'm testing, in the browser (using Shift+Refresh to force full page reload) I find changes still aren't reflected in the page and remain like this for a few minutes at least. Super-annoying when you're trying to test things and make little changes to get to the bottom of a problem etc.

I'm assuming Laravel is caching things somewhere, is there a way to switch off all caching?

For some reason I'm finding this problem is affecting even static files that the browser is loading, e.g. Javascript files, but I don't see how Laravel is affecting this, and yet Shift-Refresh in the browser doesn't work!

Any thoughts appreciated. Thanks.

05 Jul
1 year ago

ajck left a reply on Getting Unauthorized Error Trying To Send Email With Sparkpost (Laravel 5.4)

@Dave97 It's been a while since I dealt with this problem but as a quick and dirty solution I ended up putting the key directly into the source code, as below. For some reason it flatly refused to work when I put it anywhere else, I don't know why. I suspect the fix is quick and easy, but non-obvious (i.e. it should work the way we've already been trying it). Because of work pressures I left it at that, but it is a solution. When I have more time I'll try and find a better solution that puts the key back in .env! My source code is below, in case that helps. Note I just installed the SparkPost PHP library directly and bypassed Laravel entirely because it refused to work as per the rest of this thread. Install as per here: https://github.com/SparkPost/php-sparkpost#installation then I just used code below.

            // Set up Guzzle HTTP adapter:
            $httpClient = new GuzzleAdapter(new Client());
            $sparky = new SparkPost($httpClient, ['key'=> 'sparkpost_key_here_that_would_have_gone_in_env_file']);

            // Construct HTML for email from Blade template as not using Laravel email system because of the whole .env Sparkpost key problem (Not necessary for email sending as such but I need an HTML email)
            $html = view('emails.myemailtemplate')->with(['blade-template-variable1' => $some-dynamic-variable, 'blade-template-variable1' => $some-other-item-for-email])->render();

            // Send the email via SparkPost:
            $promise = $sparky->transmissions->post([
                'content' => [
                    'from' => ['name' => 'From Me!', 'email' => 'reply-to-email-address'],
                    'subject' => 'Test Email Subject',
                    'html' => $html,
                    ],
                'recipients' => [['address' => ['email' => $recipient-email-address]]],
                // If you want to switch off SparkPost email tracking so that it doesn't rewrite links in your emails to it's tracking domain:
                'options' => ['open_tracking' => false, 'click_tracking' => false]
                ]);
            try
                {
                $response = $promise->wait();
// $output = $response->getStatusCode()."<br>".print_r($response->getBody(), true); // Response code

                // Display confirmation to user
                return view('emailsent');
                }
            catch (\Exception $e)
                {
//              $output = $e->getCode()."<br>".$e->getMessage(); // Other way of getting error
                return response()->json(['error' => 'error']); // Return error to user's browser, they can try again
                }       
13 Jun
1 year ago

ajck started a new conversation Confused As To Why Collection Methods Aren't Working On What I Thought Was A Collection?

In one of my controllers, I'm getting database results via Eloquent into what I thought was a collection, and then trying to use the isNotEmpty() and transform() methods on them, but getting these errors:

(1/1) BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::isNotEmpty()

and the same error trying to use transform()

Yeah - I know, I guess Builder isn't/doesn't return a collection? So I've got "use Illuminate\Support\Collection;" at the top of my Controller. And code as below. Idea is one User can have many Appointments.

namespace App\Http\Controllers;
class ApptController extends Controller
{
        // Get appointment list for this user (initiator or recipient) from DB:
        $apptsbyme = User::find(Auth::user()->id)->appts_initiator();
        $apptsbythem =  User::find(Auth::user()->id)->appts_recipient();
dump($apptsbyme, $apptsbythem);

        if($apptsbyme->isNotEmpty())
            {
            // Get apptcode for each returned appt result, then inject into appt result so it can be accessed in blade template to generate confirm and cancel URLs:
            $apptsbyme->transform(function ($appt, $key) { 
                // Transform code
                return $appt;
            });
            }
}

and relevant bit of User model:

    // Get all of the user's appointments where they are an initiator: (one to many)
    public function appts_initiator()
        {
        return $this->hasMany('App\Appointment', 'initiator_id');
        }

    // Get all of the user's appointments where they are a recipient: (one to many)
    public function appts_recipient()
        {
        return $this->hasMany('App\Appointment', 'recipient_id');
        }

and similar for Appointment model:

    // Get user who is the initiator for this appointment: (one to many inverse)
    public function initiator_user()
        {
        return $this->belongsTo('App\User', 'initiator_id');
        }

    // Get user who is the recipient for this appointment: (one to many inverse)
    public function recipient_user()
        {
        return $this->belongsTo('App\User', 'recipient_id');
        }

Not clear why I am apparently not getting a collection back from the

$apptsbyme = User::find(Auth::user()->id)->appts_initiator();

line in the controller, or if I am why methods aren't being found on it?

I realise I am probably missing something simple but not clear what!

Thanks

29 May
1 year ago

ajck left a reply on Cashier Stripe Subscription Error - Customer Has No Attached Payment Source (L5.4)

Fixed! Stripe customer create was using input as an array $request->input['stripeEmail.... rather than a function $request->input('stripeEmail....

ajck started a new conversation Newbie Question - Where Do I Put General Functions Used By Multiple Controllers?

I've got some general 'toolbox' functions that I use in multiple Controllers. Currently I'm just duplicating the code in each controller, which I know is inefficient and bad practice. I'm still learning OOP in PHP, and Laravel, so where should I put these shared functions and how do I call them from the Controllers? Presume they get put in a class and included with 'use' at the top of the controller? Appreciate any example code if poss :) Also, if different controllers require slight variations on the code, how's best to implement that - just passing a parameter in to indicate which controller did the call and then having an 'if' block to handle the differences, or is there a better way?

Thanks

28 May
1 year ago

ajck started a new conversation Cashier Stripe Subscription Error - Customer Has No Attached Payment Source (L5.4)

I'm using Stripe Checkout on the frontend and collecting user's card details then using Cashier on the backend to subscribe the user to a pre-defined Stripe plan. I get the error

(1/1) InvalidRequest This customer has no attached payment source

and checking the Stripe Dashboard shows the user (Stripe customer) does not have any card details associated even though I pass the token through to the subscription call as per docs etc.

Front end code:

<form action="{{url('subscribe')}}" method="POST" id="stripeform1" class="nodisplay">
{!! csrf_field() !!}
<input type="hidden" name="plan" value="individual">
<input type="hidden" name="email">
<input type="hidden" name="password" value="{{$password}}" >
    <script
        src="https://checkout.stripe.com/checkout.js" class="stripe-button"
        data-key="my_stripe_test_key"
        data-image="https://myapp.co/public/images/stripeicon.png"
        data-name="MyApp"
        data-zip-code="true"
        data-locale="auto"
        data-email="[email protected]"
        data-description="Subscription for Individual Plan"
        data-currency="gbp"
        data-amount="999"
        data-label="Subscribe!">
    </script>
</form>

and back end code:

        \Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));

        // Create customer that we can then create a subscription or one-off charges for:
        $customer = \Stripe\Customer::create(['email' => $request->input['stripeEmail'], 'source'  => $request->input['stripeToken']]);

        // Attach user (as Stripe customer) to existing subscription plan defined in Stripe:
        if($request->input('plan') == 'individual') $planID = env('STRIPE_INDIVIDUAL_PLAN_ID');
        else if($request->input('plan') == 'business') $planID = env('STRIPE_BUSINESS_PLAN_ID');
        $subscription = \Stripe\Subscription::create(['customer' => $customer->id, 'items' => [['plan' => $planID]]]);

Not sure where I am going wrong, other than thinking Stripe's way of doing subscriptions changed recently (now under 'Billing') and wondering if the Cashier's Stripe API calls are out of date? (I'm on Laravel 5.4)

Thanks for any suggestions.

08 May
1 year ago

ajck left a reply on How To Define A One-way One-to-one Relationship In Eloquent?

Thanks all, noted, and appreciated.

07 May
1 year ago

ajck left a reply on How To Define A One-way One-to-one Relationship In Eloquent?

Thanks - I realise that, but what I don't get is if there needs to be a two way relationship to use Eloquent and use the hasOne relationship in my model, i.e. does there also have to be a table1_id in table2, or can I just get away with a table2_id in table1? Because I'm only interested in looking up a table2 record from a table1 record, not the other way around.

ajck started a new conversation How To Define A One-way One-to-one Relationship In Eloquent?

Think I'm missing something obvious here, but I want to define a one way, one to one relationship from table_1 to table_2, e.g. table1 schema:

        Schema::create('table1', function (Blueprint $table) {
            // Some field definitions
            $table->integer('table2_id')->unsigned();
            $table->foreign('table2_id')->references('id')->on('table2')->onDelete('cascade');
        });

Table 2 doesn't know anything about Table 1, so just has a bunch of fields defined. Model for Table 1 has:

public function table2() // Get table2 record
    {
        return $this->hasOne('App\Table2');
    }

Questions: a.) Is that relationship in the record necessary just to be able to lookup the relevant table2 record from a table1 record?

b.) How do I set the relationship in my code? Currently my controller code is:

$table_1_record = new Table1();
// What code here to define the relationship, using Eloquent? Or do I just do:
$table_1_record->table2_id = my_table2_record->id; // But this just sets it manually doesn't it, rather than using Eloquent?

c.) Is there any point in this line in the migration: $table->foreign('table2_id')->references('id')->on('table2')->onDelete('cascade'); and indeed using Eloquent at all (I want to do things the proper Laravel way), or shall I just simply manually set table2_id as in question b.) above?

Note: I don't want to define the inverse of the relationship, as I don't need to find a table_1 record from a table_2 record.

Thanks for any help.

27 Mar
1 year ago

ajck left a reply on How To Join Two Collections? (L5.4)

OK, fair enough, but how do I do what I originally stated - append a list of results (users) to another list of results, both of which are the same type, and even if there are duplicates in the results? Thanks

ajck left a reply on How To Join Two Collections? (L5.4)

Thanks but that merges rather than appends https://laravel.com/docs/5.4/collections#method-merge "If a string key in the given items matches a string key in the original collection, the given items's value will overwrite the value in the original collection:"

ajck started a new conversation How To Join Two Collections? (L5.4)

Hi, I'm building an appointments booking system, got a users table and an appointments table. Users can either be the appointment initiator (the one who creates the appointment) or the appointment recipient (the one who receives the appointment request).

I need to display a list of all appointments for a user, where they are either the initiator or the recipient, so I need to join the two separate collections I get, so I can pass that single list to the blade template to display. Using a standard one to many relationship, I have:

    // Get all of the user's appointments where they are an initiator: (one to many)
    public function appts_initiator()
        {
        return $this->hasMany('App\Appointment', 'initiator_id');
        }

    // Get all of the user's appointments where they are a recipient: (one to many)
    public function appts_recipient()
        {
        return $this->hasMany('App\Appointment', 'recipient_id');
        }

and controller code:

    public function listappointments()
        {
        // Get appt list for this user (initiator or recipient) from DB:
        $apptsinit = User::find(Auth::user()->id)->appts_initiator();
        $apptsrecpt =  User::find(Auth::user()->id)->appts_recipient();

        // NEED TO SOMEHOW JOIN/APPEND $apptsinit AND $apptsrecpt HERE TO FORM ONE COLLECTION:
        $all_appts_with_user    = ??? // Effectively $apptsinit + $apptsrecpt

        // Return view with appts (listed in blade template):
            return view('listappts', array('page' => 'listappts', $all_appts_with_user));
        }

How do I join the collections please, or is there a different way of doing this?

Thanks. Alex

29 Jan
1 year ago
24 Jan
1 year ago

ajck started a new conversation How To Set Multiple HasMany (1 To Many) Relationships On The Same Record Simultaneously?

Hi, I'm making an appointment app, a user can create an appointment at a certain date and time with another user. I have a users table and an appointments table. Each appointment has an initiator ID (the user who suggested the appointment) and a recipient ID (the user who receives the appointment request), and the models have hasMany relationships (code below)

My question is, when I create an appointment, how do I get Eloquent to associate BOTH the initiator AND the recipient with the new appointment. Looking at the syntax in the docs, I can easily do e.g. just the initiator, like so:

$initiator = User::find(Auth::user()->id); // Get user from DB who is the initiator
$appt = $initiator->appts_initiator()->create(['address' => $request->input('address'), 'whendatetime' => $request->input('whendatetime')]);

or I could do just the recipient:

$recipient = User::where('email', $request->input('email'))->first(); // Get recipient user
$appt = $recipient->appts_recipient()->create(['address' => $request->input('address'), 'whendatetime' => $request->input('whendatetime')]);

During that line with create() in it, I need to get Eloquent to associate both initiator and recipient. Or do I have to manually inject the correct ID as one of the parameters in the create(), which would seem to bypass the point of Eloquent!

Relevant model code:

class User extends Authenticatable
{
    protected $fillable = ['name', 'email', 'password'];

    // Get all of the user's appointments where they are an initiator:
    public function appts_initiator()
        {
            return $this->hasMany('App\Appointment', 'initiator_id');
        }

    // Get all of the user's appointments where they are a recipient:
    public function appts_recipient()
        {
            return $this->hasMany('App\Appointment', 'recipient_id');
        }
}

class Appointment extends Model
{
    protected $fillable = array('whendatetime', 'address', 'minuteslate');
    
    // Get user who is the initiator for this appointment:
    public function initiator_user()
        {
            return $this->belongsTo('App\User', 'initiator_id');
        }

    // Get user who is the recipient for this appointment:
    public function recipient_user()
        {
         return $this->belongsTo('App\User', 'recipient_id');
        }

    // Get the payment for this appointment:
    public function get_payment()
        {
            return $this->hasOne('App\Payment'); // Default foreign key (appointment_id)
        }
}

Thanks for any suggestions. Alex

23 Dec
1 year ago

ajck started a new conversation Using Cashier With A Different Table, Other Than Users (L5.4)?

Is there an easy way that works, to apply Cashier to a table other than users? I'm just using Cashier for subscriptions, and although I have a users table, it's not users that will subscribe, only organisations (held in their own table).

I am assuming I modify the references to user and change them to organisation, here I'm billing with Stripe): https://laravel.com/docs/5.4/billing#stripe-configuration i.e. the migration to modify users table gets changed to orgs, the Billable model references Orgs instead of Users and the API key in services.php also references the Org model:

'stripe' => [
    'model'  => App\Org::class,
    'key' => env('STRIPE_KEY'),
    'secret' => env('STRIPE_SECRET'),
],

then to create a subscription I would do:

$org= Org::find(1);

$org->newSubscription('main', 'premium')->create($stripeToken);

Anything else I'm missing?

Thanks, Alex

05 Dec
1 year ago

ajck started a new conversation Fatal Error In MimeTypeGuesser.php For Larger File Uploads? (L 5.4)

My web app does a standard file upload from the user's browser to the server, user picks file using standard file selection dialog (e.g. Windows 7), and file uploaded via AJAX. Works fine for smaller files (e.g. few hundred K) but fails for larger ones (e.g. 2 to 3 MB or less). Route is:

Route::post('imgupload', ['middleware' => 'auth', 'uses' => '[email protected]']);

Then in the controller:

    public function imgupload(Request $request)
        {
        $imgpath = $request->file('imgfile')->store('public'); // Store images locally
        
        ...etc...

error page: (1/1) FileNotFoundException The file "" does not exist in MimeTypeGuesser.php (line 123) at MimeTypeGuesser->guess('') in File.php (line 79) at File->getMimeType() in File.php (line 58) at File->guessExtension() in FileHelpers.php (line 60) at UploadedFile->hashName() in UploadedFile.php (line 34) at UploadedFile->store('public') in FilmmakerController.php (line 177) [note: 177 is the above $imgpath=... line] at FilmmakerController->imgupload(object(Request))

Any thoughts?

Thanks.

01 Dec
1 year ago

ajck left a reply on Syntax To Copy A File From Local To AWS S3?

@martinbean OK, fair enough, those are good points. I'll follow those up as an improvement. Thanks :)

ajck left a reply on Syntax To Copy A File From Local To AWS S3?

@martinbean Thanks, I appreciate the advice and take your point. However I did consider Heroku's ephemeral storage quite carefully, e.g. the official docs: https://devcenter.heroku.com/articles/dynos#ephemeral-filesystem . I'm only using the local storage for a fraction of a second, within the space of a single request - the likelihood of that particular dyno being lost within a request at that particular fraction of a second, is not worth bothering about I think. And the official docs do say we can use the storage :) Also, I'm not going to install more bloat into Laravel to do something I can achieve in a couple of lines of native PHP, and I wonder in the background how that package is doing what it's doing. Also seems slightly nuts to pull the image down after uploading it to S3, when at the very least the temp file uploaded from the user's browser is already on the dyno's local storage! But thanks :)

30 Nov
1 year ago

ajck started a new conversation Syntax To Copy A File From Local To AWS S3?

What's the best way to copy an uploaded file from my Laravel installation (running on Heroku) to S3? I can't do a direct to S3 upload, as it's an image that I'm locally generating a thumbnail for. I also don't want to use any extra libraries etc. (sledgehammer to crack a nut etc.). File needs to go in a particular folder in my S3 bucket. Is this the only/best way? :-

Storage::disk('s3')->put('S3_folder_name/file.jpg', file_get_contents('my_local_file.jpg'));

Thanks

03 Nov
1 year ago

ajck started a new conversation Can I Write Directly To Amazon S3 As A File Path In PHP's GD Library ImageJPEG Function (or Others)?

My webapp takes uploaded images, processes them a bit, then writes them out using PHP's GD library functions such as imageJPEG http://uk1.php.net/manual/en/function.imagejpeg.php which take a direct filepath as an argument. This worked fine on my local dev machine, but I'm now switching to storing the images on Amazon S3 directly (as I'm moving to running the site in production on Heroku).

Judging by the Laravel docs https://laravel.com/docs/5.4/filesystem#storing-files it looks like I probably need to use those specific functions to have any interaction with S3 and therefore I need to think about writing uploaded images on the server then writing them immediately to S3 (then deleting the local copy). Is this correct, or is there a more direct way of doing this?

I also need to ensure the files are publicly accessible when written (I guess using Storage::putfile() with the visibility argument)

Thanks for any advice.

25 Oct
1 year ago

ajck left a reply on How Do I Query By Geolocation In Laravel 5?

@angeloj That's a good idea, but what does the final select statement look like - can you paste any code please?

Also, should the 2nd part of your statement above reference longitude rather than latitude? E.g.

...AND longitude_int IN(".int(($longitude10^7)-$distance_square).",".int(($longitude10^7)+$distance_square).")

Thanks

07 Oct
1 year ago

ajck left a reply on How To Get Laravel To Return Correct HTTP Response To Trigger JQuery $.ajax() Success?

OK, fixed it! In case anyone else comes across the same issue... basic problem was JQuery's success block only gets triggered for 200 OK (which I had) and if it can deserialise the response, which I take to mean response is in the same format as the AJAX request which in my case is JSON, but I was returning MIME type text/plain. So the fix was in my Laravel response code, changing it to:

return response()->json(['ok' => 'ok']); // Return OK to user's browser

More info here: https://stackoverflow.com/a/14114816/4059141

ajck left a reply on How To Get Laravel To Return Correct HTTP Response To Trigger JQuery $.ajax() Success?

@Snapey @Cronix thanks very much - good suggestions which I've now tried but unfortunately makes no difference. I am definitely hitting the correct code on the back end in Laravel as it's doing the things it's supposed to, and if I modify the response sent back it appears in the JS console but is always triggering JQuery's error block rather than success block, and yes the response is definitely an HTTP 200 OK code. Hmmm....

06 Oct
1 year ago

ajck started a new conversation How To Get Laravel To Return Correct HTTP Response To Trigger JQuery $.ajax() Success?

I'm doing an AJAX POST of a simple HTML form using JQuery on my front end, to my Laravel back end, and upon success want to return the correct response to trigger JQuery's $.ajax() 'success' block rather than it's 'error' block. Unfortunately whatever I try seems to trigger the 'error' block.

My route is:

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

Back end:

public function signup()
    {
    [main code]
    return response('OK', 200); // I also tried return response('OK', 200)->header('Content-Type', 'text/plain');
    }

Front end:

$('#signupbtn').click(function(e)
{
$.ajax({
    headers: { 'X-CSRF-TOKEN': $('#signup-form > input[name="_token"]').val() },
    type: 'POST',
    url: 'signup',
    data: { email: $('#email').val(), name: $('#name').val() },
    dataType: 'json',
    success: function (data)
        {
        console.log(data);
        $('#signupmodal').modal('hide'); // Close sign up modal
        $('#thanksmodal').modal(); // Open thanks modal
        },
    error: function (data)
        {
        console.log('Error:', data.responseText);
        }
    });
});

Also, if I DO want to trigger the $.ajax() 'error' block, what's the correct Laravel code for that?

Thanks.

29 Sep
1 year ago
28 Sep
1 year ago

ajck started a new conversation How To Model Guests In A (hotel) Booking? (not One-to-many Relationship?)

I have an accommodation booking site and in my database I have a guests table and a bookings table, and I need to relate a booking to the specific guests for that booking. There could potentially be any number of guests.

The obvious solution on the face of it would be a one (booking) to many (guests) relationship as per here: https://laravel.com/docs/5.4/eloquent-relationships#one-to-many but this then sets a foreign key on a guest tying it to that specific booking. But of course guests will make many bookings over time so each guest record can not be permanently hard wired to a specific booking.

My idea therefore was simply to store guest IDs in a string on the booking separated by pipes '|' and do a 'manual' lookup when I want to find guests associated with a booking. But is there a better way of modelling this (in either SQL or Laravel or Eloquent)? I'm using MariaDB/MySQL as the database, if that makes any difference.

Thanks

26 Sep
1 year ago

ajck left a reply on Getting Unauthorized Error Trying To Send Email With Sparkpost (Laravel 5.4)

@adamprickett Thanks. I've got SPARKPOST_SECRET set correctly in my .env so it's:

MAIL_DRIVER=sparkpost MAIL_HOST=smtp.sparkpostmail.com MAIL_PORT=587 MAIL_USERNAME=my-sparkpost-account-login-email-address MAIL_PASSWORD=my-sparkpost-account-login-password MAIL_ENCRYPTION=tls SPARKPOST_SECRET=my_sparkpost_API_key

I'm guessing the MAIL_HOST should be something else?

On a separate note, I'm confused why the docs https://laravel.com/docs/5.4/mail don't mention any of this and clearly don't work!

Thanks

ajck started a new conversation Getting Unauthorized Error Trying To Send Email With Sparkpost (Laravel 5.4)

I've been following the Laravel Mail docs https://laravel.com/docs/5.4/mail to send email via a SparkPost account. When I try and send I'm getting

ClientException
Client error: `POST https://api.sparkpost.com/api/v1/transmissions` resulted in a `401 Unauthorized` response:
{"errors": [ {"message": "Unauthorized."} ]}

As per the docs I've got the sparkpost key in config/services.php and though the docs don't mention anything about it (why not!?) a bit of Googling convinced me to set the mail driver etc. in my .env file. I then have a web route to check the config being used,

Route::get('test', function()
{
    dd(Config::get('mail'));
});

which gives

array:9 [▼
  "driver" => "sparkpost"
  "host" => "smtp.sparkpostmail.com"
  "port" => "587"
  "from" => array:2 [▶]
  "encryption" => "tls"
  "username" => "my-sparkpost-account-login-email-address"
  "password" => "my-sparkpost-account-login-password"
  "sendmail" => "/usr/sbin/sendmail -bs"
  "markdown" => array:2 [▶]
]

I actually want to use a mailable and views which I've set up, but just to test the sending I bypassed these and set the following route to test:

Route::get('/sparkpost', function () {
  Mail::send('emails.test', [], function ($message) {
    $message
      ->from('[email protected]', 'Me')
      ->to('my-email-address', 'My-Name')
      ->subject('A Test Email');
  });
});

which got the error at the top (testing with my mailables and views gave the exact same error which makes me think they are correctly set up - assuming the above test route is correct).

The on thing I'm wondering about is I'm testing on my local machine, so test URL is http://localhost/seg/public/sparkpost - I'm wondering if this is tripping SparkPost up (i.e. do I have to actually be sending from a server running at the same domain as the sending domain configured in sparkpost, or is it just the sending address in the email that has to match?)

Thanks for any suggestions!

20 Sep
1 year ago

ajck left a reply on How To Model Availability In A Simple Hostel Booking System? (Laravel 5.4)

Thanks. I don't get the 'grouped by date' bit - how am I storing the availability for each separate day for a year (or two)? Any example code? :)

Thanks

ajck started a new conversation How To Model Availability In A Simple Hostel Booking System? (Laravel 5.4)

I've got a simple hostel booking system and am not sure how to model availability in the database (e.g. via Eloquent). A hostel is simpler than a hotel as for booking purposes it's effectively just one big room. However there will be multiple hotels in the database (run by different owners). So my current database tables are: Guests, Hostels (includes owner details), Bookings (i.e. person W staying at hostel X from date Y to date Z), and Payments (payment amount for a stay). Obviously these are tied together (e.g. with ID references or some other relationship).

But with availability I need to represent the number of beds available for a specific hostel on any date for e.g. the next year or two. What's an efficient way to do that?

Thanks for any suggestions.

18 Sep
1 year ago

ajck left a reply on How To Integrate Stripe Checkout With Laravel (5.4) Cashier?

@martinbean Just wondering - any idea how to get the payment amount from the stripeToken that's returned from the payment form submitted by Stripe Checkout? Reason being that I have three different subscription options with three subscribe buttons and need a way to know which was submitted (so I know which plan to sign the user up to) without it being easily hackable. At the moment I've just got a hidden field with the plan name in each of the subscribe button forms. Any user could e.g. open developer options in their browser and change the hidden field plan name (thus e.g. paying the price of the basic subscription for the gold plan!). Thanks

ajck left a reply on How To Integrate Stripe Checkout With Laravel (5.4) Cashier?

@martinbean This has been extremely helpful, thanks very much, especially the last chunk of code. Appreciated!

11 Sep
1 year ago

ajck started a new conversation How To Integrate Stripe Checkout With Laravel (5.4) Cashier?

Hi, I'd like my site visitors to be able to sign up to one of three simple subscription plans, paying with a credit/debit card. I've set up Laravel Cashier on the back end, and the default Stripe Checkout on the frontend, and am now just trying to finish the back end Laravel code to tie the two together. I've been following an example Stripe 'recipe' and am looking at the bit where the server receives the Stripe token from the Stripe checkout popup on the front end, here: https://stripe.com/docs/recipes/subscription-signup#create-a-subscription-for-the-customer and trying to match that up with the bit in the Laravel docs about creating a subscription: https://laravel.com/docs/5.4/billing#creating-subscriptions

So I'm effectively trying to merge those two bits of code at those two links (amazed that I can't find anything online about it anywhere given it's using all the standard default Laravel and Stripe stuff!). I'm not sure exactly what code to write. Guessing it's something like the below?

\Stripe\Stripe::setApiKey("my_stripe_secret_key");
$user = User::find(1);
$user->newSubscription('main', 'premium')->create($stripeToken);

1.) What about the try...catch block in the Stripe example code? (at the aforementioned link) - if the payment fails, how does Laravel handle that, or how do I handle that in the Laravel code?

2.) The Stripe example code posts the customer's email from the Checkout form, back to Stripe to create the customer, but the Laravel example code doesn't supply email, so I'm not clear on whether this is really necessary or not (for Stripe, or for my database).

Basically, the end result I want is as advertised in the two docs - a new customer and subscription entered into the database on both my server, and in Stripe, and Stripe to bill the customer - i.e. all the default standard stuff :)

Thanks for any suggestions!

21 Jul
1 year ago

ajck left a reply on How To Get Correct Path To An Uploaded Image File To Pass To A PHP Function?

@jlrdw by asset helper do you mean asset() function?

Laravel is installed where composer put it - as a newbie to Laravel I just trusted it I have to say, and no idea how to move everything now...

How/where would I use asset() in my code above?

Thanks

ajck started a new conversation How To Get Correct Path To An Uploaded Image File To Pass To A PHP Function?

I'm trying to access an image file (uploaded with AJAX) to a Laravel 5.4 backend, and having trouble getting native PHP functions to access it. File is uploading fine (appears in the correct upload folder) but Laravel error reports that PHP's getimagesize() can't find the file) Actual error is:

(1/1) ErrorException
getimagesize(storage/public/images/viE9JvY8jfA4fVuZL7vkh3RdZY0zyT4svH4Xldv1.jpeg): failed to open stream: No such file or directory

Partial code is below:

public function imgupload(Request $request)
    {
    // Store file from 'imgfile' field from uploaded form (imguploadform in blade template) in /storage/app/public/images/
        $path = $request->file('imgfile')->store('public/images');
    // Generate a thumbnail from the image using PHP's inbuilt GD library and store in thumbs dir:;     
    $thumbpath = $this->makethumbs($path);
        
        return response()->json(['thumb' => asset($thumbpath)]); // Return path 
    }

// Reads full size uploaded image from storage, generates a smaller thumbnail and saves it to the thumbs/ dir
public function makethumbs($img, $maxwidth = 120, $maxheight = 120)
    {
    $img = 'storage/app/'.$img;
    $arr_image_details = getimagesize($img);

    /* Other stuff to generate thumbnail here */

    // Write thumbnail image out to thumbs/ folder

    return($thumbnail_path);
    }

This is on my local Windows 7 laptop (tho will need to work online later, probably Heroku). I'm running on Bitnami's WAMP stack, and root Laravel folder is apache2/htdocs/seg . In there, public/ contains a folder link called 'storage' which maps to storage/app/ and that folder contains public/ then in there folders images/ and thumbs/ . So intention is to read uploaded image out of images/ then resize and put into /thumbs.

I did a few Log:info()'s and found $path (in my imgupload func) is: public/images/viE9JvY8jfA4fVuZL7vkh3RdZY0zyT4svH4Xldv1.jpeg

and in makethumbs() PHP's current working dir (via getcwd()) is: C:\Bitnami\wampstack-7.1.2-0\apache2\htdocs\seg\public

So if getimagesize() is starting from PHP's working dir, in theory it should be looking in: C:\Bitnami\wampstack-7.1.2-0\apache2\htdocs\seg\public/storage/public/images/[filename] C:\Bitnami\wampstack-7.1.2-0\apache2\htdocs\seg\storage\app\public\images

Any ideas welcome!

12 Jul
2 years ago

ajck left a reply on How To Display HTML User Input In A Blade Template Without Risking XSS Attacks?

@jlrdw Great answer, I'd forgotten about that. Thanks

11 Jul
2 years ago

ajck started a new conversation How To Display HTML User Input In A Blade Template Without Risking XSS Attacks?

I'm getting the contents of some rich text editor fields in a form then storing in the database and want to display them via a blade template later. The rich text editor ( http://ckeditor.com/ ) output is HTML but in the blade template if I use {{ }} statements obviously this is escaped and doesn't display correctly when I output it. If I use {!! !!} statements it's not escaped and displays correctly but apparently I'm at risk of XSS attacks (as per red warnings just below here: https://laravel.com/docs/5.4/blade#displaying-data )

Is there a way around this?

Thanks