MattB

MattB

Member Since 4 Months Ago

Experience Points 2,220
Experience Level 1

2,780 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 1
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.

19 Sep
12 hours ago

MattB started a new conversation How Does The View Composer Work With Multiple Queries

Right, so on a site I'm doing, there are multiple queries running to the database and returning different results. I'm using these everywhere but I would like to know how the view composer can be used for this. I have seen it work for one query but I don't know how to use it for the following:

$segaCategories = Category::where('company', 'sega')->get();
      $nintCategories = Category::where('company', 'nintendo')->get();
      $psCategories = Category::where('company', 'ps')->get();
      $xboxCategories = Category::where('company', 'xbox')->get();
      $amigaCategories = Category::where('company', 'amiga')->get();
      $atariCategories = Category::where('company', 'atari')->get();
      $bitCategories = Category::where('company', '8-Bit')->get();
      $doCategories = Category::where('company', '3DO')->get();
      $cdiCategories = Category::where('company', 'CDi')->get();
      $neoCategories = Category::where('company', 'Neo-Geo')->get();
      $pcEngineCategories = Category::where('company', 'PCengine')->get();
      $pcCategories = Category::where('company', 'PC')->get();
      $gawCategories = Category::where('company', 'Game And Watch')->get();
      $importCategories = Category::where('company', 'Imports')->get();
      $merchCategories = Category::where('company', 'Merchandise')->get();
      $holidayMessage = Holiday::where('set', 1)->get();

I understand the following can be used for one query but I don't know how to use it for the above:

view()->composer('*', function($view){
            $view->with();
        });

(also, do wildcards work like I have in the 2nd code block?)

12 Sep
1 week ago

MattB left a reply on Password Reset Issue

Is this something just native to Laravel 6 or does 5.8 have it?

11 Sep
1 week ago

MattB started a new conversation Password Reset Issue

So, I have a password reset view which relies on a variable being passed into it. I tried to use the below Route but it meant that when I go to the "Login" link, the button for "Forgot Your Password" is missing:

Route::get('/password/reset', 'Auth\[email protected]')->name('reset');

When I remove that route, the button comes back but of course, the link complains about a missing variable.

The function in the controller is:

public function showResetForm()
    {
        $categoryMenu = Categories::all();
        return view('auth.passwords.reset', compact('categoryMenu'));
    }

MattB left a reply on Trying To Get Property 'name' Of Non-object

This didn't bring back any results now, the cell is just blank in the table

10 Sep
1 week ago

MattB started a new conversation Trying To Get Property 'name' Of Non-object

So, I have a pivot table connecting 2 other tables together. I'm trying to access the property of NAME through that table but I'm getting the "Trying to get property 'name' of non-object" error. I think it might be something to do with the relationships but I could be wrong?

View:

 @if($orderItems)
        <table class="table table-hover table-bordered" id="usersTable">
            <thead>
            <tr>
                <th>id</th>
                <th>SKU</th>
                <th>Product</th>
                <th>Price</th>
            </tr>
            </thead>
            <tbody>
            @foreach($orderItems as $item)
                <tr>
                    <td>{{$item->id}}</td>
                    <td>{{$item->product_id}}</td>
                    <td>{{$item->product->name}}</td>
                    <td>£{{$item->price}}</td>
                </tr>
            @endforeach
            </tbody>
        </table>
        {{ $orderItems->links() }}
    @endif

Controller:

public function show($id)
    {
        $orderItems = CartItem::where('admin_order_id', $id)->paginate(5);
        return view('admin.orders.show', compact('orderItems'));
    }

Model

class CartItem extends Model
{
    public function AdminOrders(){
      return $this->belongsTo('App\AdminOrders', 'admin_order_id');
    }
    public function Products(){
      return $this->belongsTo('App\Products', 'product_id');
    }
}

Migration:

public function up()
    {
        Schema::create('cart_items', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('admin_order_id');
            $table->integer('product_id');
            $table->integer('price');
            $table->timestamps();
        });
    }

MattB left a reply on How To Delete From Drop Down List

Ah that got it. Many MANY thanks for the help!

MattB left a reply on How To Delete From Drop Down List

Actually the 'response()->back gives this error sorry:

Method Illuminate\Routing\ResponseFactory::back does not exist.

MattB left a reply on How To Delete From Drop Down List

Ok that works to show the page again thanks, but when I try to remove anything from the list with the below function, it 404s and doesn't delete anything

 public function destroy(Request $request)
    {
        Company::findOrFail($request->company_id)->delete();
        return response()->back();
    }

Tried redirect()->back and redirect('admin/brands') but get the same 404

MattB left a reply on How To Delete From Drop Down List

<?php

namespace App\Http\Controllers;

use App\AdminBrands;
use App\Company;
use Illuminate\Http\Request;

class AdminBrandsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $allBrands = Company::all();
        return view('admin.brands.index', compact('allBrands'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
           'brand' => 'required',
        ]);
        $brands = new Company();
        $brands->company = $request->brand;
        $brands->save();
        return redirect()->back()->with('message', 'Brand Added');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\AdminBrands  $adminBrands
     * @return \Illuminate\Http\Response
     */
    public function show(AdminBrands $adminBrands)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\AdminBrands  $adminBrands
     * @return \Illuminate\Http\Response
     */
    public function edit(AdminBrands $adminBrands)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\AdminBrands  $adminBrands
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, AdminBrands $adminBrands)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\AdminBrands  $adminBrands
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        Company::findOrFail($request->company_id)->delete();
        return response()->back();
    }
}

MattB left a reply on How To Delete From Drop Down List

All it says is

     * Merge the collection with the given items.
     *
     * @param  \ArrayAccess|array  $items
     * @return static
     */
    public function merge($items)
    {
        $dictionary = $this->getDictionary();
 
        foreach ($items as $item) {
            $dictionary[$item->getKey()] = $item;
        }
 
        return new static(array_values($dictionary));
    }
 
    /**
     * Run a map over each of the items.
     *
     * @param  callable  $callback
     * @return \Illuminate\Support\Collection|static
     */
    public function map(callable $callback)
    {
        $result = parent::map($callback);
 

MattB left a reply on How To Delete From Drop Down List

Now i get

Call to a member function getKey() on string (View: C:\xampp\htdocs\EdenBeauty\resources\views\admin\brands\index.blade.php)

MattB left a reply on How To Delete From Drop Down List

@extends('layouts.admin')

@section('content')
    <h1 class="display-3">Brands</h1>
    <br><br>
   <div class="row">
       <div class="col-4 offset-2">
           <h1 class="display-4">Brands:</h1>
           {!! Form::open(['method'=>'DELETE', 'action'=> '[email protected]']) !!}
               <div class="form-group {{$errors->has('company_id') ? 'has-error' : ''}}">
                   {!! Form::select('company_id', [''=>'Choose Brand'] + $allBrands,null, ['class'=>'form-control'])!!}
                   @if($errors->has('company_id'))
                       {{$errors->first('company_id')}}
                   @endif
               </div>
           <div class="form-group">
               {!! Form::submit('Remove Selected Brand', ['class'=>'btn btn-danger']) !!}
           </div>
           {!! Form::close() !!}
       </div>
           <div class="col-4">
               <h1 class="display-4">Add new:</h1>
               <br>
               @if(session()->has('message'))
                   <div class="alert alert-success alert-dismissible fade show">
                       <button type="button" class="close" data-dismiss="alert">&times;</button>
                       {{ session()->get('message') }}
                   </div>
               @endif
               {!! Form::open(['method' =>'POST', 'action'=> '[email protected]', 'files'=>true, 'enctype'=>'multipart/form-data']) !!}
               <div class="form-group {{$errors->has('brand') ? 'has-error' : ''}}">
                   {!! Form::text('brand', null, ['class'=>'form-control'])!!}<br>
                   @if($errors->has('brand'))
                       <div class="alert alert-danger alert-dismissible fade show">
                           {{$errors->first('brand')}}
                       </div>
                   @endif
               </div>
               <div class="form-group">
                   {!! Form::submit('Add Brand', ['class'=>'btn btn-primary']) !!}
               </div>
               {!! Form::close() !!}
           </div>
       </div>
   </div>
@endsection

MattB left a reply on How To Delete From Drop Down List

This is just when I go to the index.blade which houses the drop down list. removed the 'destroy' => 'admin.brands.destroy', but still same error

MattB left a reply on How To Delete From Drop Down List

Ok so I'm using

Route::delete('admin/brands', '[email protected]')->name('admin.brands.destroy');
    Route::resource('admin/brands', 'AdminBrandsController', ['names' => [
        'index' => 'admin.brands.index',
        'create' => 'admin.brands.create',
        'store' => 'admin.brands.store',
        'edit' => 'admin.brands.edit',
        'show' => 'admin.brands.show',
        'destroy' => 'admin.brands.destroy',
    ]])->except(['destroy']);

now, but get error

Object of class Illuminate\Database\Eloquent\Collection could not be converted to int (View: C:\xampp\htdocs\EdenBeauty\resources\views\admin\brands\index.blade.php)

Have I not followed you correctly?

MattB left a reply on How To Delete From Drop Down List

Sorry, I thought this would work but I can't figure out the routing part. I'm using

Route::resource('admin/brands', 'AdminBrandsController', ['names' => [
        'index' => 'admin.brands.index',
        'create' => 'admin.brands.create',
        'store' => 'admin.brands.store',
        'edit' => 'admin.brands.edit',
        'show' => 'admin.brands.show',
        'destroy' => 'admin.brands.destroy',
    ]]);

But I get error

Missing required parameters for [Route: admin.brands.destroy] [URI: admin/brands/{brand}]. (View: C:\xampp\htdocs\EdenBeauty\resources\views\admin\brands\index.blade.php)
09 Sep
1 week ago

MattB left a reply on How To Delete From Drop Down List

Oh, ok. No other way around it then?

MattB left a reply on How To Delete From Drop Down List

Thats the thing, its not a loop. I'm just passing in $allBrands in order to make the drop down list without looping through it, which I realize is causing the error with it not being a loop, but I don't see a way out of it

MattB started a new conversation How To Delete From Drop Down List

I'm having a brain fart here. I have a list that's built from the entries in a table, which has a delete button beneath it. I want to be able to hit that button and delete whatever is selected in the list. So far I have this:

{!! Form::open(['method'=>'DELETE', 'action'=> ['[email protected]', $allBrands->id]]) !!}
               <div class="form-group {{$errors->has('company_id') ? 'has-error' : ''}}">
                   {!! Form::select('company_id', [''=>'Choose Brand'] + $allBrands,null, ['class'=>'form-control'])!!}
                   @if($errors->has('company_id'))
                       {{$errors->first('company_id')}}
                   @endif
               </div>
           <div class="form-group">
               {!! Form::submit('Remove Selected Brand', ['class'=>'btn btn-danger']) !!}
           </div>
           {!! Form::close() !!}

Controller:

public function index()
    {
        $allBrands = Company::pluck('company', 'id')->all();
        return view('admin.brands.index', compact('allBrands'));
    }

When I try to use the code as-is, I get error

Trying to get property 'id' of non-object

I can't see how to pass in the variable correctly it seems?

06 Sep
1 week ago

MattB left a reply on Sending Custom Emails

Will this allow the columns from bootstrap to work?

MattB started a new conversation Sending Custom Emails

How would one go about sending a custom email? I have an ecommerce shop but would like to know how to customise the email sent to customers showing all they have bought. The below email works but I was wondering if there was a better way, as when it's sent the bootstrap link won't work until the customer allows it when they open the mail, and I can appreciate not all people are comfortable allowing all links:

@component('mail::message')
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
   Thank you for your purchase. Please find the details of your order below:
   <br>
   <br>
        <div class="row">
            <div class="col-4">Product Name</div>
            <div class="col-4">Price</div>
            <div class="col-4">Quantity</div>
        </div>
        @foreach($emailItems as $item)
        <div class="row">
            <div class="col-4">{{ $item->name}}</div>
            <div class="col-4">£{{ $item->price}}</div>
            <div class="col-4">{{ $item->quantity}}</div>
        </div>
        @endforeach
04 Sep
2 weeks ago

MattB left a reply on Mail Not Finding Mail Class

Oh for... Sorry yeah, blind. Wasted your time really....

MattB left a reply on Mail Not Finding Mail Class

Still no joy. My ide is saying App\Mail\ContactUs and Mail are undefined classes. Here's the contents of ContactUs:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class ContactMail extends Mailable
{
    use Queueable, SerializesModels;
    public $data;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->markdown('emails.contactForm');
    }
}

MattB left a reply on Mail Not Finding Mail Class

Tried that but it didn't work. Same error

MattB started a new conversation Mail Not Finding Mail Class

Ok so I'm trying to send a mail with this controller but when I hit send on the form to call the controller I get a message saying the ContactUs class is not found, even though ContactUs.php is indeed in App\Mail

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Mail\ContactUs;
use Illuminate\Support\Facades\Mail;


class ContactUSController extends Controller
{
    public function contactUSPost(Request $request)
    {
        $data = request()->validate([
            'name' => 'required',
            'email' => 'required|email',
            'number' => 'required',
            'message' => 'required'
        ]);
        Mail::to('[email protected]')->send(new ContactUS($data));
        return back()->with('complete', 'Thanks for contacting us!');
    }
}

Have I made an obvious mistake here?

30 Aug
2 weeks ago

MattB started a new conversation How To Pass Variable From Register Controller

So, I have this function:

public function showRegisterForm()
    {
        $categoryMenu = Categories::all();
        return view('auth.register', compact('categoryMenu'));
    }

which should pass $categoryMenu into the view I want. However when I use this as a route:

Route::get('register', [ 'as' => 'register', 'uses' => '[email protected]']);

I get told

Class App\Http\Controllers\RegisterController does not exist

Which it does as I was editing it. Have I gone about this the wrong way? I did the exact same thing with the login controller and it worked fine...

28 Aug
3 weeks ago

MattB started a new conversation GroupBy Not Showing A Full Array

I have this query which looks like it loops through the array just fine, but in the DD, it only shows the first element in the group by array. When on the front end I try to loop through the array it creates, I only get the first result too

public function show(Company $id)
    {
        $allProducts = Products::findorFail($id);
        $companies = Company::all();
        $title = $id->company;
        $categories = Products::where('company_id', $id->id)->groupBy('category_id')->get();
        dd($categories);
        return view('allProducts', compact('allProducts', 'companies' ,'title', 'categories'));
    }
22 Aug
4 weeks ago

MattB left a reply on Tracking Sent Emails

I'm using the mail_host of n3plcpnl0067.prod.ams3.secureserver.net - seems to be one set up through cPanel but when I check the mail address I have in the env file on cpanel mail account, I don't see anything in sent, even though I know it has sent other successful mails

MattB left a reply on Tracking Sent Emails

I think its mailgun but on their site it asks for a login. I never signed up with them. Am I looking in the wrong place?

MattB started a new conversation Tracking Sent Emails

Is there a way to see what emails have been sent from laravel mailer to email addresses at all? A mail didn't reach it's the recipient but others did. Just wondering if I can see it has been sent

09 Aug
1 month ago

MattB left a reply on File Upload Limit Issues

Nope all I have is this:

public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
            'image'       => 'required',
            'name'        => 'required',
            'description' => 'required',
            'price'       => 'required',
        ];
    }

Confused to heck with this one

MattB left a reply on File Upload Limit Issues

No nothing in storage/logs and nothing obvious in the server logs either

I have the memory limit already at it's max which is 512mb

MattB left a reply on File Upload Limit Issues

Are these in the php.ini file too? It doesn't seem to even try uploading the larger files. When I click upload it more or less instantly switches to the uploaded files page

MattB left a reply on When To Use Vue On Your Laravel Project ?

I could be way off the mark here but I assume using Vue for the front end offloads a lot of the work from the server onto the client's browser and let it do all the work

MattB started a new conversation File Upload Limit Issues

I have a form which is used to upload a .zip file to my server. I can upload smaller ones (~200mb), but when I go to upload larger ones (nearer or above 1GB), the page will redirect from the upload form to the page showing the uploads, but the file I just uploaded doesn't show, nor does it make it to the database. I was having actual messages when I first started saying the post was too large but I changed 2 files as below and now there's no error, just nothing uploads. Where did I go wrong?

php.ini which is in the same folder as .htaccess:

post_max_size=2048M
upload_max_filesize=2048M

Also, in the .htaccess file, I added this:

php_value post_max_size 2048M;
php_value upload_max_filesize 2048M;
    
php_value client_max_body_size 2048M;
php_value client_body_buffer_size 2048M;

I would really appreciate your help with this one.

08 Aug
1 month ago

MattB left a reply on Holiday Message Issue

Just had a brainwave as I posted. Fixed with

@foreach($holidayMessage as $hMessage)
<div class="alert alert-danger text-center" role="alert">
  {{$hMessage->message}}
</div>
@endforeach

MattB started a new conversation Holiday Message Issue

I have the following set up to display a message on the condition that the column in the db called "set" is set to 1 which works ok. However if I set that column to 0 it still shows a blank alert instead of hiding the div. What do?

<div class="alert alert-danger text-center" role="alert">
  @foreach($holidayMessage as $hMessage)
  {{$hMessage->message}}
@endforeach
</div>
$holidayMessage = Holiday::where('set', 1)->get();  
  return view('home', compact('holidayMessage'));

MattB started a new conversation Adding A Holiday Message

What's the best way to go about this:

Customer needs a message they can turn on and off in the admin panel which would show them as being on holiday. I was thinking of having it just as a bootstrap alert which would display only when activated in the back end. I know I can set a table up with a column for an "active" flag to set to 1 or 0 but this seems very heavy-handed.

Is there a more eloquent way of doing this, so they can turn it off and on, and maybe set their own message?

07 Aug
1 month ago

MattB left a reply on Increase File Upload Size

Ok but when I log in to cPanel and then file manager, I don't seem to be able to see the php.ini file when I search. Should it be in file manager or elsewhere?

MattB started a new conversation Increase File Upload Size

How do I increase the file upload in Laravel? I saw somewhere about editing the php.ini but a: I can't find it in my laravel project and b: some confusion about the code to use. Can you help, please?

02 Aug
1 month ago

MattB started a new conversation How To Use Paypal API Credentials With Srmklive Laravel Package

Not sure if you can help here but I would really appreciate if you could. I am using the srmklive package for Laravel and have set up a sandbox account on the Paypal API dashboard and it works. I am trying to port it over to use the customer's live business account on Paypal but I can't map across the API credentials. The sandbox uses the following:

PAYPAL_CLIENT_ID=
PAYPAL_CLIENT_SECRET=
PAYPAL_MODE=

But all I see when I generate the details on Paypal business account is

API Username
API Password
Signature

I don't know if these sets of details are equivalent or if there is something else I need to be doing?

16 Jul
2 months ago
15 Jul
2 months ago

MattB started a new conversation Updating Table Column Based On Paypal Package Return

Currently, I'm using the Paypal package from srmklive which almost entirely working except I would like it to update a specific column in my database when it returns with the successful payment. I have this so far on my controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Game;
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Rest\ApiContext;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Input;
use PayPal\Api\PaymentExecution;

use Session;

class PaymentController extends Controller
{
    //
    private $api_context;
    public function __construct()
    {
      /** PayPal api context **/
        $paypal_conf = \Config::get('paypal');
        $this->_api_context = new ApiContext(new OAuthTokenCredential(
            $paypal_conf['client_id'],
            $paypal_conf['secret'])
        );
        $this->_api_context->setConfig($paypal_conf['settings']);
      }
      public function paypalWrapper(){
        $cart = Session::get('cart');
        return PaymentController::payWithpaypal($cart);
      }
      public function payWithpaypal($cart){
        $payer = new Payer();
        $payer->setPaymentMethod('paypal');
        $item_list = new ItemList();
        foreach($cart->items as $item){
          $item_1 = new Item();
          $item_1->setName($item['item']['title'] . ' SKU: ' . $item['item']['id']) /** item name **/
          ->setCurrency('GBP')
          ->setQuantity($item['qty'])
          ->setPrice($item['price']); /** unit price **/
          $item_list->addItem($item_1);
        }
        $amount = new Amount();
        $amount->setCurrency('GBP')
               ->setTotal($cart->totalPrice);
      $transaction = new Transaction();
              $transaction->setAmount($amount)
                  ->setItemList($item_list)
                  ->setDescription('Your transaction description');
      $redirect_urls = new RedirectUrls();
              $redirect_urls->setReturnUrl(URL::route('paymentsuccess')) /** Specify return URL **/
                  ->setCancelUrl(URL::route('home.index'));
      $payment = new Payment();
              $payment->setIntent('Sale')
                  ->setPayer($payer)
                  ->setRedirectUrls($redirect_urls)
                  ->setTransactions(array($transaction));
              /** dd($payment->create($this->_api_context));exit; **/
              try {
      $payment->create($this->_api_context);
      } catch (\PayPal\Exception\PPConnectionException $ex) {
      if (\Config::get('app.debug')) {
      \Session::put('error', 'Connection timeout');
                      return Redirect::route('paywithpaypal');
      } else {
      \Session::put('error', 'An error has occured, sorry for the inconvenience');
                      return Redirect::route('paywithpaypal');
      }
      }
      foreach ($payment->getLinks() as $link) {
      if ($link->getRel() == 'approval_url') {
      $redirect_url = $link->getHref();
                      break;
      }
      }
      /** add payment ID to session **/
              Session::put('paypal_payment_id', $payment->getId());
      if (isset($redirect_url)) {
      /** redirect to paypal **/
                  return Redirect::away($redirect_url);
      }
      \Session::put('error', 'Unknown error occurred');
              return Redirect::route('paywithpaypal');
      }

      public function getPaymentStatus(Request $request)
    {
        /** Get the payment ID before session clear **/
        $payment_id = Session::get('paypal_payment_id');
        /** clear the session payment ID **/
        Session::forget('paypal_payment_id');
        if (empty(Input::get('PayerID')) || empty(Input::get('token'))) {
        \Session::put('error', 'Payment failed');
            return Redirect::route('home.index');
        }
        $payment = Payment::get($payment_id, $this->_api_context);
        $execution = new PaymentExecution();
        $execution->setPayerId(Input::get('PayerID'));
        /**Execute  the payment **/
        $result = $payment->execute($execution, $this->_api_context);
        if ($result->getState() == 'approved') { 
        $itemSearch = Game::findOrFail($request->id);
          dd($itemSearch);
          $input = $request->all();                   
          \Session::put('success', 'Payment success');
          Session::forget('cart');
            return redirect()->route('thankyou.index');
        }
        \Session::put('error', 'Payment failed');
        return Redirect::route('home.index');
    }
}

I have put in the DD there to capture the request to work out how to get the ID from it but when the request comes back from Paypal, it just 404s.

This is how the cart is put together:

<?php

namespace App;

class Cart
{
    public $items = null;
    public $totalQty = 0;
    public $totalPrice = 0;

    public function __construct($oldCart){
      if ($oldCart){
        $this->items = $oldCart->items;
        $this->totalQty = $oldCart->totalQty;
        $this->totalPrice = $oldCart->totalPrice;
      }
    }

    public function add($item, $id){
      $storedItem = ['qty' =>0, 'price' => $item->price, 'item' => $item, 'id' => $id];
      if ($this->items) {
        if (array_key_exists($id, $this->items)) {
          $storedItem = $this->items[$id];
        }
      }
      $storedItem['qty']++;
      $storedItem['price'] = $item->price * $storedItem['qty'];
      $this->items[$id] = $storedItem;
      $this->totalQty++;
      $this->totalPrice+=$item->price;
    }

    public function removeItem($id){
      $this->totalQty -= $this->items[$id]['qty'];
      $this->totalPrice -= $this->items[$id]['price'];
      unset($this->items[$id]);
    }
}
12 Jul
2 months ago

MattB left a reply on Paypal API Not Posting Item Array

Anybody that can help? Really out of my depth with this one

MattB started a new conversation Paypal API Not Posting Item Array

I have set up a Paypal API that grabs the price and item details from a shopping cart I have set up and then sends the price over to Paypal to charge the customer. However, although all the details of the items do show in the response header, they never get sent over to Paypal.

Here is the code responsible for grabbing the details:

<script>
    paypal.Buttons({
     createOrder: function(data, actions) {
       // Set up the transaction
       return actions.order.create({
         purchase_units: [{
           amount: {
             value: {{ $totalPrice }},
             currency: 'GBP',
             item_list:{
               items: [
                  @foreach($products as $product)
                  {
                    name: "{{ $product['item']['title'] }}",
                    sku: {{ $product['id'] }},
                    quantity: 1,
                    unit_amount: {
                      currency_code: "GBP",
                      value: {{ $product['price'] }}
                    }
                  },
                  @endforeach
              ],
             }
           },
         },
       ]
       });
     },
     onApprove: function(data, actions) {
      // Capture the funds from the transaction
      return actions.order.capture().then(function(details) {
        // Show a success message to your buyer
        alert('Transaction completed by ' + details.payer.name.given_name);
        console.log(data.orderID);
        return fetch('{{ route('PaypalServerController.getOrder')}}', {
          method: 'post',
          _token: '{{csrf_token()}}',
          headers: {
            'content-type': 'application/json'
          },
          body: JSON.stringify({
            orderID: data.orderID
          })
        }).then(function(){
          alert('SUCCESS!');
        }, function(){
          alert('IT FAILED');
        });
      });
    }
   }).render('#paypal-button-container');
  </script>

And here is the controller

  public function authenticate(request $request){
    return 'authenticate test';
  }
  public static function getOrder(request $request)
  {
    $orderId = json_decode($request->getContent())->orderID;
    // 3. Call PayPal to get the transaction details

    $client = PayPalClient::client();
    $response = $client->execute(new OrdersGetRequest($orderId));
    /**
     *Enable the following line to print complete response as JSON.
     */
    //print json_encode($response->result);
    print "Status Code: {$response->statusCode}\n";
    print "Status: {$response->result->status}\n";
    print "Order ID: {$response->result->id}\n";
    print "Intent: {$response->result->intent}\n";
    print "Links:\n";
    foreach($response->result->links as $link)
    {
      print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
    }
    // 4. Save the transaction in your database. Implement logic to save transaction to your database for future reference.
    print "Gross Amount: {$response->result->purchase_units[0]->amount->currency_code} {$response->result->purchase_units[0]->amount->value}\n";

    // To print the whole response body, uncomment the following line
    // echo json_encode($response->result, JSON_PRETTY_PRINT);
  }
}

/**
 *This driver function invokes the getOrder function to retrieve
 *sample order details.
 *
 *To get the correct order ID, this sample uses createOrder to create a new order
 *and then uses the newly-created order ID with GetOrder.
 */
if (!count(debug_backtrace()))
{
  PaypalServerController::getOrder('REPLACE-WITH-ORDER-ID', true);
}

What I expected to happen was for when the customer logs into the Paypal window that pops up, that the item details show there. Also on the Paypal account screen for the vendor, for the items to show there too. Is this possible?

09 Jul
2 months ago

MattB left a reply on Pulling ID Into Form Within Modal

I did this but for some reason, as @dalma rightly said, it's pulling just the last ID listed. How do I get around this, please?

MattB left a reply on AJAX Login With 'password' Authentication To Allow Length Of 4 Instead Of 6?

What about using

 'password' => 'required|confirmed|min:4', 
08 Jul
2 months ago

MattB started a new conversation Pulling ID Into Form Within Modal

I have an edit form in a modal that's set to use the ID number from a table. For some reason, regardless of what entry is clicked, it will always pull in the same ID for some reason. Here are the table and the modal/form:

@extends('layouts.admin')
@section('content')
  <h1>Games <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addNew">Add New</button></h1>
  @if($games)
<table class="table table-hover table-bordered" id="usersTable">
    <thead>
      <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Image</th>
        <th>Price</th>
        <th>Category</th>
        <th>Sold?</th>
        <th>Promote?</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
      @foreach($games as $game)
      <tr>
        <td>{{$game->id}}</td>
        <td>{{$game->title}}</td>
        <td><img src="{{$game->image}}" alt="" width="50"></td>
        <td>£{{$game->price}}</td>
        <td>{{$game->category->name}}</td>
        <td>{{$game->sold}}</td>
        <td>{{$game->promote}}</td>
        <td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#editGame">Edit</button></td>
      </tr>
      @endforeach
    </tbody>
  </table>

@endif
<div class="modal fade" id="addNew" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
  <div class="modal-content">
    <div class="modal-header">
      <h5 class="modal-title">Add Game</h5>
      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      {!! Form::open(['method' =>'POST', 'action'=> '[email protected]', 'files'=>true, 'enctype'=>'multipart/form-data']) !!}
      @include('includes.admin.gameForm')
      <div class="form-group">
        {!! Form::submit('Add Game', ['class'=>'btn btn-primary']) !!}
      </div>
      {!! Form::close() !!}
    </div>
  </div>
</div>
</div>

<!--EDIT GAME SECTION-->
<div class="modal fade" id="editGame" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
  <div class="modal-content">
    <div class="modal-header">
      <h5 class="modal-title">Edit Game</h5>
      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      {!! Form::model($game, ['method' =>'PATCH', 'action'=> ['[email protected]', $game->id], 'files'=>true, 'enctype'=>'multipart/form-data']) !!}
      @include('includes.admin.gameForm')
      <div class="form-group">
        {!! Form::submit('Update Game', ['class'=>'btn btn-primary']) !!}
      </div>
      {!! Form::close() !!}
    </div>
  </div>
</div>
</div>
@stop

It's using this from the controller:

$games = Game::all();
        $categories = Category::pluck('name', 'id')->all();
        return view('admin.games.index', compact('games', 'categories'));

Also on a follow-up, is this the right way to go about updating the database based off the form input?

$gameSearch = Game::findOrFail($id);

          $file = $request->file('image');
          if($file){
            $name = $file->getClientOriginalName();
            if($file->move('images/games/', $name)){
              $games->image = '/images/games/' . $name;
              $games->title = $request->title;
              $games->price = $request->price;
              $games->category_id = $request->category_id;
              $games->promote = $request->promote;
              $games->sold = 0;
              $gameSearch->update($games);
              return redirect()->route('/admin');
            };
          };
07 Jul
2 months ago

MattB left a reply on How Eloquent Relations Work

Ah brilliant, thank you!

MattB started a new conversation How Eloquent Relations Work

I know that when you create a model using php artisan make:model Modelname -m it will pluralize the model name when it creates the migration. But when the name ends in "y" it will make the migration name end with ies as per english grammar.

I know that if you want to join 2 tables using the 2nd table's id column, you would place columnName_id in the first table and eloquent works out the connection.

so for example, if I had a model name "category" it would create "categories" as the migration name for the table. Would I put in category_id and let eloquent work it out, or would it need to be categories_id?