MattB

MattB

Member Since 2 Months Ago

Experience Points 1,210
Experience Level 1

3,790 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.

16 Jul
6 days ago
15 Jul
1 week 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
1 week 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
1 week 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 Update Default 'password' Authentication To Allow Length Of 4 Instead Of 6?

What about using

 'password' => 'required|confirmed|min:4', 

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?

08 Jul
2 weeks 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 weeks 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?

04 Jul
2 weeks ago

MattB started a new conversation SQLSTATE[42S02]: Base Table Or View Not Found:

I have an issue with the admin side of a site I'm doing. I have included on the admin side 4 links but when I click on any of them I get this error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'sonic.admins' doesn't exist (SQL: select * from admins where id = peripherals limit 1)

I have no idea where that SQL query is coming from as I am not running any to my knowledge

I'm using the following controller as an example of one broken link:

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

but

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

works fine. I'm using the out-of-the-box controller for AdminGamesController and using the following links:

<div class="list-group list-group-flush">
  <a href="{{route('home.index')}}" class="list-group-item list-group-item-action"><i class="fas fa-home"></i>&nbsp;&nbsp;Home</a>
  <a href="{{route('games.index')}}" class="list-group-item list-group-item-action"><i class="fas fa-home"></i>&nbsp;&nbsp;Games</a>
  <a href="{{route('figures.index')}}" class="list-group-item list-group-item-action"><i class="fas fa-user-friends"></i>&nbsp;&nbsp;Figures</a>
  <a href="{{route('guides.index')}}" class="list-group-item list-group-item-action"><i class="fas fa-user-friends"></i>&nbsp;&nbsp;Guides</a>
  <a href="{{route('peripherals.index')}}" class="list-group-item list-group-item-action"><i class="fas fa-user-tie"></i>&nbsp;&nbsp;Peripherals</a>
</div>
03 Jul
2 weeks ago

MattB left a reply on Where Query Returning Blank Results

@NAKOV - I'm using

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

MattB left a reply on Where Query Returning Blank Results

@NAKOV - Clicked on best answer by mistake, but this didn't work I'm afraid

MattB started a new conversation Where Query Returning Blank Results

I have the following code which is bringing back a blank set of results and I can't see why:

public function show(Request $games)
    {
      $allGames = Games::where('category', $games)->get();
      dd($allGames);
      // return view('games', compact('games'));
    }

There are entries in the "Games" table and I'm pretty sure I'm passing in the correct argument to the request with:

@foreach($categories as $category)
          <li><a href="{{route('games.show', $category->id)}}">{{$category->category}}</a></li>
          @endforeach

as this does place "games/1" in the URL for example. Can't see what I've done wrong

02 Jul
2 weeks ago

MattB left a reply on New Controller For Each Page

Ok, I'm assuming this is for the web.php file? I've only ever used this for defining stuff as per this:

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

How do I use the code you've provided to pass to the view for each game category?

MattB started a new conversation New Controller For Each Page

I'm putting together a catalog site for retro games and there are about 30 categories (consoles) that games sell under. My question is, do I need to create a different controller and route for each category or is there a more streamlined way to do it Laravel. Basically, each category page will show a list of games under that category that are for sale, from the database and an option to buy.

20 Jun
1 month ago

MattB left a reply on Issue Submitting Form Data From Bootstrap 4 Modal

@MSTRAUSS - This didn't work I'm afraid. This is a really odd issue

MattB left a reply on Issue Submitting Form Data From Bootstrap 4 Modal

Ok so the result of that is that I do get everything passed from the form

MattB left a reply on Issue Submitting Form Data From Bootstrap 4 Modal

Ok so I have added the DD in the correct place in the UsersRequest and get the response there

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
            'username'=>'required',
            'email'=>'required',
            'password'=>'required',
            'firstName'=>'required',
            'lastName'=>'required',
            'role'=>'required',
            dd(request()->all())
        ];

    }
}

But when I remove the dd it's back to not submitting

MattB left a reply on Issue Submitting Form Data From Bootstrap 4 Modal

@MSTRAUSS - Ok it's odd. Here is the controller. When I include the DD in the "UsersRequest" request file, it says "Class App\Http\Requests\UsersRequest does not exist" but it does exist, spelled correctly as per below reference

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\UsersRequest;

use App\User;
use App\Role;

class UsersController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        return view('admin.users.index');
    }

    /**
     * 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(UsersRequest $request)
    {
        //
        // if(trim($request->password) == ''){
        //   $input = $request->except('password');
        // } else{
        //   $input = $request->all();
        //   $input['password'] = bcrypt($request->password);
        // }

        // $file_image = $request->file('image');
        // if($file_image){
        //   $name = $file_image->getClientOriginalName();
        //   $path_images = 'images';
        //   if($file_image->move($path_images, $name)){
        //     $post = new User();
        //     $post->image = '/' . $name;
        //     $post->firstName = $request->firstName;
        //     $post->lastName = $request->lastNfgfame;
        //     $post->email = $request->email;
        //     $post->username = $request->username;
        //     $post->role = $request->role;
        //     $post->save();
        //     return redirect()->route('admin.users.index');
        //   };
        // };
        dd(request()->all());
        // return view('Welcome');
    }

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

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

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
19 Jun
1 month ago

MattB left a reply on Issue Submitting Form Data From Bootstrap 4 Modal

@MSTRAUSS - ``` public function store(UsersRequest $request) {

    dd(request()->all());
   
}

MattB left a reply on Issue Submitting Form Data From Bootstrap 4 Modal

@REPULSOR - Ok it seems it's something to do with the custom requests file I've added for validation. When I set it back to the default one, it works fine. This is the custom request form:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
            'username'=>'required',
            'email'=>'required',
            'password'=>'required',
            'firstName'=>'required',
            'lastName'=>'required',
            'role'=>'required',
        ];
    }
}

And it is called here:

public function store(UsersRequest $request)
    {   
        dd(request()->all());
    }

but it doesn't like my request file?

MattB left a reply on Issue Submitting Form Data From Bootstrap 4 Modal

@NAKOV - Nope, nothing. Doesn't return the error. It looks like it's not even calling the @store method at all. When I hit submit then go back to the form after the page refreshes, the data is still there

MattB started a new conversation Issue Submitting Form Data From Bootstrap 4 Modal

I cannot get data to submit from a modal in laravel. When I use the below code and hit the 'add user' button, the modal just closes and doesn't seem to call the @store method in my controller. Data doesn't get submitted to the db

<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">New User</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']) !!}
        <div class="form-group {{$errors->has('firstName') ? 'has-error' : ''}}">
          {!! Form::label('firstName', 'First Name:') !!}
          {!! Form::text('firstName', null, ['class'=>'form-control', 'rows' => 3])!!}
          @if($errors->has('firstName'))
            {{$errors->first('firstName')}}
          @endif
        </div>
{{--most form data removed for simplicity--}}
        <div class="form-group">
          {!! Form::submit('Add user', ['class'=>'btn btn-primary']) !!}
        </div>
        {!! Form::close() !!}
      </div>      
    </div>
  </div>
</div>
03 Jun
1 month ago

MattB started a new conversation Populating 2 Divs From Laravel Search

Is there a way to use Blade templates to fill in 2 divs from a single eloquent search? For example, could I use the following query:

$homeGallery = Gallery::where('patreon', 0)->take(6)->orderBy('created_at', 'desc')->get();
        return view('home', compact('homeGallery'));

to then populate 2 divs to do the blade equivalent of:

<div class="col-md-8">
    <div class="row">
        <div class="col-md-4"><img src="image1" class="previewimage img-thumbnail mx-auto d-block"></div>
        <div class="col-md-4"><img src="image2" class="previewimage img-thumbnail mx-auto d-block"></div>
        <div class="col-md-4"><img src="image3" class="previewimage img-thumbnail mx-auto d-block"></div>
    </div>
<div class="row">
        <div class="col-md-4"><img src="image4" class="previewimage img-thumbnail mx-auto d-block"></div>
        <div class="col-md-4"><img src="image5" class="previewimage img-thumbnail mx-auto d-block"></div>
        <div class="col-md-4"><img src="image3" class="previewimage img-thumbnail mx-auto d-block"></div>
    </div>
</div>

Can an @foreach loop auto fill the above, or is there another way to do it? It must be a two-row, three-column grid

MattB left a reply on / Protected Buy Something

@SERGIU17 - It shows

public function __construct()
    {
        $this->middleware(['auth', 'verified']);
    }

MattB started a new conversation / Protected Buy Something

So I have a site which uses the '/' route to display the home page but it keeps asking for you to log in. I want to have the ability to have people log in but not force them to just to see the home page as it is now. Right now the web.php file snippet for the home controller looks like this:

Auth::routes();
Route::auth();

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

Here's my route list, which hints it's being protected by "auth" and "verified" but is there a way to turn this off, and is this wise?

# php artisan route:list
+--------+-----------+------------------------------------------------+------------------------------+------------------------------------------------------------------------+----------------------+
| Domain | Method    | URI                                            | Name                         | Action                                                                 | Middleware           |
+--------+-----------+------------------------------------------------+------------------------------+------------------------------------------------------------------------+----------------------+
|        | POST      | /                                              | home.store                   | App\Http\Controllers\[email protected]                              | web,auth,verified    |
|        | GET|HEAD  | /                                              | home.index                   | App\Http\Controllers\[email protected]                              | web,auth,verified    |
31 May
1 month ago

MattB left a reply on Issue Sending Password Reset Mails

@BOBBYBOUWMANN - Yeah nothing in the logs sadly. I'm not the expert here, but I saw nothing in the sent items of the inbox I'm sending from which tells me it's not even trying to be sent, not that it's being caught by the spam filter. I'm using the port details given by the provider, and when I use the wrong details on purpose it flags it as an error so I don't know if the details are wrong

30 May
1 month ago

MattB started a new conversation Issue Sending Password Reset Mails

As titled, I cannot get Laravel to send password reset emails. I am using the "out of the box" auth command to handle the password reset and I put in all the details from the email account I set up in cpanel. Laravel will authenticate the details ok and will tell me the reset link has been sent ok but the email hasn't been sent from the mail account and it doesn't show in the target email either. I don't know what I've done wrong but here's my code section from the .env file:

MAIL_DRIVER=smtp
MAIL_HOST=n3plcpnl0067.prod.ams3.secureserver.net
MAIL_PORT=465
MAIL_USERNAME=**account address**
MAIL_PASSWORD=**acount password**
MAIL_ENCRYPTION=ssl

and from the mail.php file:

'driver' => env('MAIL_DRIVER', 'smtp'),
'host' => env('MAIL_HOST', 'n3plcpnl0067.prod.ams3.secureserver.net'),
'port' => env('MAIL_PORT', 465),
'from' => [
        'address' => env('MAIL_FROM_ADDRESS', '[email protected]'),
        'name' => env('MAIL_FROM_NAME', 'Password reset'),
    ],

First time doing this and I don't know what I've done wrong. It works fine when I use the dummy account on mailtrap. Any help greatly appreciated

03 May
2 months ago

MattB started a new conversation Storage To 2 Places

Can "file -> move" be used to pass in a 2nd argument so that the same form can push requested files to 2 different locations? What I have right now is:

if($file = $request->file('image')){
          $name = $file->getClientOriginalName();
          $path = 'images';
          if($file->move($path, $name)){
            $newartpack = new artpack();
            $newartpack->thumbnail = '/' . $path . '/' . $name;
            $newartpack->name = $request->name;
            $newartpack->description = $request->description;
            $newartpack->price = $request->price;
            $newartpack->save();
            return redirect()->route('admin.artpacks.index');
          };
        };

This just handles one image upload, but can I do something like this to also accept and move a zip file to go along with it:

if($file = $request->file('image')){
          $name = $file->getClientOriginalName();
          $pathOne = 'images';
      $pathTwo = 'some other path here';
          if($file->move($pathOne, $pathTwo, $name)){
            $newartpack = new artpack();
            $newartpack->thumbnail = '/' . $pathOne . '/' . $name;
            $newartpack->artzip = '/' . $pathTwo . '/' . $name;
            $newartpack->name = $request->name;
            $newartpack->description = $request->description;
            $newartpack->price = $request->price;
            $newartpack->save();
            return redirect()->route('admin.artpacks.index');
          };
        };
02 May
2 months ago

MattB started a new conversation Upload/downloading Of Zip Files

Is there a way to create a form field to upload and download zip files to and from the Laravel Database? Say I want to create a zip of pictures to sell which I can upload to the site, then have a link to the zip file to download?

30 Apr
2 months ago

MattB left a reply on Catching Wildcards In Routes

@MARTINBEAN - Ok so right now, the code I'm using to upload is thus:

public function store(Request $request){
        //
        if($file = $request->file('image')){
          $name = $file->getClientOriginalName();
          $path = 'images';
          if($file->move($path, $name)){
            $post = new Gallery();       
            $post->image = '/' . $path . '/' . $name;
            $post->name = $request->name;
            $post->species_id = $request->species_id;
            $post->tag = $request->tag;
            $post->patreon = $request->patreon;
            $post->save();
            return redirect()->route('AdminGallery.gallery.index');
          };
        };
    }

Which gives me the following file path in the database and the image shows fine on the site but isn't caught by the route noted above:

Database link: /images/IMG_1415.JPG
Link in HTML: <img src="/images/IMG_1415.JPG">

However if I use the below:

public function store(Request $request){
        //
        if($file = $request->file('image')){
          $name = $file->getClientOriginalName();
          $path = '../gallery';
          if($file->move($path, $name)){
            $post = new Gallery();
            $post->image = $path . '/' . $name;
            $post->name = $request->name;
            $post->species_id = $request->species_id;
            $post->tag = $request->tag;
            $post->patreon = $request->patreon;
            $post->save();
            return redirect()->route('AdminGallery.gallery.index');
          };
        };
    ```

the path in the db breaks becoming

../gallery/Delphian_Calamity_by_alexiuss.jpg


and not showing on the site

MattB left a reply on Catching Wildcards In Routes

@MARTINBEAN - Ah ok so if I wanted to reference the folder from the controller (say I name the folder images and put it in the same folder as the 'public' folder) so it can be updated in the db, how would I do it?

MattB left a reply on Catching Wildcards In Routes

@MARTINBEAN - The URL is site.test/images/(any image name here). I'm using the below route:

Route::get('/images/{matchAll?}', function(){
  return 'NOPE';
})->where('matchAll', '.*');

There's no special response, it just shows the image when I wanted to block it

MattB left a reply on Catching Wildcards In Routes

No, that's at the top of the web.php file and no other route references /images/

29 Apr
2 months ago

MattB left a reply on Catching Wildcards In Routes

@TALINON - Just tried that and oddly didn't work. Have I missed something else?

MattB left a reply on Catching Wildcards In Routes

Yeah, that's fine but what if I wanted to have the path /images/(anything else here) re-directed somewhere else?

MattB started a new conversation Catching Wildcards In Routes

Is there a way to route based on wildcards? For example, is there a way to route somewhere if the user types in an address from the images folder? I was trying the below but that didn't seem to work:

Route::when('/images/*', function(){
  return 'NOPE';
});
26 Apr
2 months ago

MattB left a reply on Odd Image Upload Issue

@MAVERICKCHAN - I'm sorry that still didn't work. I need that line due to the image being shown on the admin page as per:

@foreach($gallery as $images)
    <tr>
      <td width="20%"><img height="50" src="{{$images->image}}"></td>
      <td>{{$images->name}}</td>
      <td>{{$images->species['name']}}</td>
      <td>{{$images->tag == 1 ? 'Yes' : 'No'}}</td>
      <td>{{$images->patreon == 1 ? 'Yes' : 'No'}}</td>
      <td width="10%">
        {!! Form::open(['method'=>'DELETE', 'action'=> ['[email protected]', $images->id]]) !!}
        <div class="form-group">
          {!! Form::submit('Delete', ['class'=>'btn btn-danger']) !!}
        </div>
        {!! form::close() !!}
      </td>
    </tr>
    @endforeach

If I use {{ asset('images/' . $gallery->image) }} in here, I get error "Property [image] does not exist on this collection instance."

MattB left a reply on Odd Image Upload Issue

That didn't work I'm afraid. What's odd is that the same images every time fails to load. When it does work, it's always the same ones that do work. I bet it's some issue with the image but I fail to see what

MattB left a reply on Odd Image Upload Issue

Ah that works to bring the images back but still not all. Some still show as 404

MattB left a reply on Odd Image Upload Issue

@MICHALURVA - I tried it as

<li><p>{{$gallery->name}}</p><a href="asset('images/'.$gallery.name);" target="_blank"><img src="asset('images/'.$gallery.name);" alt="" class="img-thumbnail" width="200" height="400"></a></li>

but now none of the pictures show. Have I misunderstood massively?

MattB started a new conversation Odd Image Upload Issue

I have an odd issue with displaying the result of a file upload form. Below is the code for the upload:

public function store(Request $request){
        //
        if($file = $request->file('image')){
          $name = $file->getClientOriginalName();
          $path = 'images';
          if($file->move($path, $name)){
            $post = new Gallery();
            $path = '../public/images';
            $post->image = $path . '/' . $name;
            $post->name = $request->name;
            $post->species_id = $request->species_id;
            $post->tag = $request->tag;
            $post->patreon = $request->patreon;
            $post->save();
            return redirect()->route('admin.gallery.index');
          };
        };
    }

It uploads all the images ok, but when I display them with the following code, some will show on the page as expected, but some show a 404 error. They are showing in the folder specified ok and in the db, it's showing the correct file path (correct path in the Chrome dev console too). I have no idea what's going on here.

@extends('layouts.app')

@section('content')
  <div class="container galleryContainer">
    <br>
    <div class="display-4">Gallery</div><br>
    <ul class="galleryList">
      @foreach($mainGallery as $gallery)
      <li><p>{{$gallery->name}}</p><a href="{{$gallery->image}}" target="_blank"><img src="{{$gallery->image}}" alt="" class="img-thumbnail" width="200" height="400"></a></li>
      @endforeach
    </ul>
  </div>
  @endsection
25 Apr
2 months ago

MattB left a reply on Image Uploads To Tmp Instead Of Correct Location

@DUNSTI - Ah ha! Thank you very much, much appreciated

MattB left a reply on Image Uploads To Tmp Instead Of Correct Location

@DUNSTI - Hi, thanks for the reply, but I'm afraid I don't understand sorry. What would the new line look like?

MattB started a new conversation Image Uploads To Tmp Instead Of Correct Location

Using the below code, it should upload to the path specified in $path but for some reason, it saves the links to all pictures to c:\xampp\tmp with the .tmp extension but will move them to the correct folder anyway. What have I done wrong?

public function store(Request $request){
        //
        if($file = $request->file('image')){
          $name = $file->getClientOriginalName();
          $path = 'public/images';
          if($file->move($path, $name)){
            $post = new Gallery();
            $post->image = $request->image;
            $post->name = $request->name;
            $post->species_id = $request->species_id;
            $post->tag = $request->tag;
            $post->patreon = $request->tag;
            $post->save();
            return redirect()->route('admin.gallery.index');
          };
        };
    }