elliotk

elliotk

Member Since 2 Years Ago

Experience Points 17,640
Experience Level 4

2,360 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 151
Lessons
Completed
Best Reply Awards 1
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.

27 Apr
2 months ago

elliotk left a reply on Laravel Forge - Nginx Respond On IP

@xsecrets i don't know why i didn't think to spin up another server, anyway I got the config from that one and copied it over - job done.

26 Apr
2 months ago

elliotk left a reply on Laravel Forge - Nginx Respond On IP

Anyone give me a lift on this one?

25 Apr
2 months ago

elliotk left a reply on How To Dynamic- "Bootstrap Multi Column Carousel" Using Laravel Please Help...

I have something similar in my application but for displaying products. Here is a stripped version, I hope it helps. Note I am using chunk and not take.

At the Controller, I am passing only $products which could be 1, 10 or 50.

  @foreach ($products->chunk(4) as $productCollection)

  <!-- Product Row Start -->
  <div class="row">

    @foreach ($productCollection as $product)
<!-- Display Product -->
<h2>{{ $product->title }}</h2>
<img src="{{ $product->image }}" />
<!-- End Product Display -->
    @endforeach

</div>
<!-- End Product Row -->

@endforeach

elliotk left a reply on Checking Multiple Table For Unique Validation

To allow a user to update their own record and not throw a unique error, you can pass the ID of the user as an extra parameter so that row ID is ignored in the check.

'email' => 'required|email|unique:users,email,'. $user->id,

elliotk started a new conversation Laravel Forge - Nginx Respond On IP

I have been using Forge for some time, with my servers behind a load balancer (Digital Ocean). DO is currently configured to do a simple check of port 80 using TCP. This detects if the server is online and nginx running, but not if php-fpm is up or whether there is database connectivity etc.

I'd like to change this to do health checks via HTTP, that way I can make some simple checks of the server and return a 200 if all is good and keep the server in the pool.

It seems when I try and access the Forge server via IP (rather than domain), i get a nginx 404, which causes DO to remove the server from the pool as its expecting a 200. Can anyone help me configure a new site in nginx that would respond on IP and load a simple php script in a given path eg /var/www/html

Any help appreciated.

Elliot

07 Nov
8 months ago

elliotk left a reply on Sort And Paginate

Heres the paginate solutions

{!! $products->appends(\Request::except('page'))->render() !!}

I hope all this helps someone else too

elliotk left a reply on Sort And Paginate

So, I sorted the query..

$products = $category->products()->enabled()->with('media')
            ->when(request('sort'), function ($query) {
                    return $query->orderBy(request('sort'), request('order'));
                })->paginate(12);

And then on the front end I've done this

      <div class="form-group">
        <select class="form-control" name="sort" id="sort" onchange="if (this.value) window.location.href=this.value">
          <option value="?sort=name&order=asc">Name [A-Z]</option>
          <option value="?sort=name&order=desc">Name [Z-A]</option>
          <option value="?sort=price&order=asc">Price [Low-High]</option>
          <option value="?sort=price&order=desc">Price [High-Low]</option>
        </select>
      </div>

This does the correct sorting, so that's good. The issue now is that when I move to the second page on the paginate, the sorts are dropped from the URL and the results that are displayed are unsorted.

Any ideas?

elliotk left a reply on Sort And Paginate

Thanks @dalma i don't want to go to the java / ajay way, i'd much rather do something in the controller.

I'm thinking something like this, but can't get the syntax right.

        $products = $category->products()->enabled()->with('media');

        if (request('sort') && request('order')) {
            $products->orderBy(request('sort'), request('order'));
        }

        $products->paginate(12);

I think on the front end, i can do a simple dropdown, which does a redirect to the page with the query parameters appended.

elliotk left a reply on Sort And Paginate

Anybody got a moment to review this?

06 Nov
8 months ago

elliotk left a reply on Filters For Different Categories Using Many-to-many Relationship

I think you need to look at hasManyThrough

https://laravel.com/docs/5.7/eloquent-relationships#has-many-through

class Category extends Model
{
    public function filters()
    {
        return $this->hasManyThrough('App\Filters', 'App\Products');
    }
}

Then you can use $category->filters();

Thanks

elliotk started a new conversation Sort And Paginate

Hello,

I am hoping for some help and advice on sorting. I have a Category page which lists out Products which I paginate.

    public function view(Category $category)
    {   
        $category->load('media');
        $products = $category->products()->enabled()->with('media')->paginate(12);
        return view('shop.category.index', compact('category','products'));
    }

I now want to provide the option to sort the products on the category page.

Product->Name (A-z) Product->Name (Z-a) Product->Price (Low-High) Product->Price (High-Low)

What is the best way of accomplishing this? I'd considered a drop down box, wrapped by a form, which posts to the server, however I don't want any warnings about resubmitting if the user doesn't navigate properly.

I guess something like mysite.com/laptops?page=2&sort=price&price=asc would be ideal.

Any pointers how to do this in my route, controller and blade?

Thanks

03 Nov
8 months ago

elliotk left a reply on Paginate Eager Loaded Relationship

Thanks @Snapey that did the trick

elliotk started a new conversation Paginate Eager Loaded Relationship

Hello,

I am trying to get pagination working for Products here. Where I have the paginate(6) at the moment, the correct number of Products are returned, although I don't know if it's the correct place to put it.

However, I have tried all sorts to get the links() to show in blade, and I can't figure it out.

Is there a special way with Eager Loaded relations?

class CategoryController extends Controller
{
    public function view(Category $category)
    {
        $category->load(['products' => function ($products) {
            $products->enabled()->with('media')->paginate(6);
        }])->with('media');

        return view('shop.category.index', compact('category'));
    }
}
02 Nov
8 months ago

elliotk left a reply on Moving Associated Records Between Models

This would only work presuming that there were no roles() already on $user2, which unfortunately there are

01 Nov
8 months ago

elliotk started a new conversation Moving Associated Records Between Models

Hello,

Say I have a Many to Many Relationship between Users and Roles and I wanted to move any Roles from User 1 to User 2 how would I do this?

Something like this?

$user2->roles()->attach($user2->roles()->pluck('id'));

What about if I also had additional data in the pivot? For example

$user1->roles()->->attach($roleId, ['expires' => $expires]);

How would you take the old pivot value and attach that over to the new user, carrying the roles and the pivot values from user1 to user 2?

Thanks for any advice.

29 Oct
8 months ago

elliotk left a reply on Help Optimising Query

That makes sense, and the issue at git makes for an interesting read too.

I'm going to take your suggestion and do it in blade, since i'll be caching anyway.

The fact that my code creates 4 sql queries seems fine in this case too.

Thanks for all your help!

elliotk left a reply on Help Optimising Query

Ok that makes sense.

So to only return one Category per Product where should the first() be?

When i put it inside the closure, only 1 of the 6 returned Products has a Category, the other 5 are empty. If I remove the it, all 6 Products return 2 Categories each (which would be correct).

        $products = Product::enabled()->promote()->with('media')
                            ->with(['categories' => function ($categories) {
                                 $categories->enabled()->first()->with('media');
                            }])->inRandomOrder()->take(6)->get();

I could leave it without the first() and do that in blade, as I will cache the results anyway, but would be nice to bottom it out.

elliotk left a reply on Help Optimising Query

@Cronix your solution worked to fix the blade stuff, thanks for that.

I am so lost on this query though.. I'm wondering if I need the closure at all now...

Let me explain what I need, maybe it will help formulate a query.

Product model using the following query scopes: scopeEnabled and scopePromote

with Media (on the Product model) for reference it's spatie/laravel-medialibrary

with Categories modal using the following query scopes scopeEnabled but only the first() Category that the product falls in.

with Media (on the Category model)

and then only for 6 random products (currently) using take(6)

elliotk started a new conversation Help Optimising Query

Hello,

I need some help optimising a query, and putting the correct syntax in to blade. At the moment, I am generating 12 SQL queries. I know 6 of them, come from blade, but the other 6, I am a bit lost on.

    public function index()
    {   
        $products = Product::with('media')->enabled()->promote()->inRandomOrder()->take(6)
                            ->with(['categories' => function ($categories) {
                                 $categories->with('media')->enabled()->first();
                            }])->get();

        //return response()->json($products);
        
        return view('home', compact('products'));
    }

This returns all the correct data I need...

https://ek1.ams3.digitaloceanspaces.com/1.png

However, in blade, with the debugbar it gets awfully messy...

https://ek1.ams3.digitaloceanspaces.com/2.png

The first 6, I presume are to do with my above query - is that normal? Can it be improved? Of course I can cache it, but at the moment I am trying to optimise the queries themselves.

I know that the bottom 6 are due to the following line, but not sure how to correct that in my blade...

<a href="/{{ $product->categories()->first()->slug}}/{{ $product->slug }}">

I would have presumed that the first() wouldn't execute another query given the data is already passed, but I am fairly new to Laravel.

Any advice greatly received.

28 Oct
8 months ago

elliotk started a new conversation Redis - Undefined Index: Driver

Hello,

I am trying to get up and running with Redis for the first time. I'm using Forge, and currently, all my caching is to file. I thought it was as simple as changing the CACHE_DRIVER but perhaps I am wrong?

I ssh in to my server to check for Redis

[email protected]:~$ redis-cli ping
PONG

Seems Redis is running.

So i update my CACHE_DRIVER=redis

It then blows up

ErrorException (E_NOTICE)
Undefined index: driver

I have checked my cache.php seems to be ok

'redis' => [

            'client' => 'predis',

            'default' => [
                'host' => env('REDIS_HOST', 'localhost'),
                'password' => env('REDIS_PASSWORD', null),
                'port' => env('REDIS_PORT', 6379),
                'database' => 0,
            ],

        ],

And I have installed predis too via composer require predis/predis

Have I missed something obvious?

27 Oct
8 months ago

elliotk started a new conversation Redirect With /link#deeplink

Hello,

I am using Bootstrap 4 Tabs / Pills

https://getbootstrap.com/docs/4.1/components/navs/#javascript-behavior

I have some javascript which updates the URL of the page - see here: https://webdesign.tutsplus.com/tutorials/how-to-add-deep-linking-to-the-bootstrap-4-tabs-component--cms-31180

When I use redirect()->back(); in my controller, the #element gets stripped off my URL. Any idea how to retain it so I can go back to the tab that the user was active on?

THanks

25 Oct
8 months ago

elliotk left a reply on Many To Many In Many To Many

@Snapey thanks for the response, I wasn't clear enough in my question so I have updated it.

elliotk started a new conversation Many To Many In Many To Many

Hello,

I have a Product model, which belongs to many Categories. I also have a Discount model which belongs to many Categories.

How can I list all the Products that a given Discount has attached?

Thanks

elliotk left a reply on Verification Emails

thanks @Snapey that did the trick!

elliotk started a new conversation Verification Emails

Hello,

I've upgraded from 5.6 to 5.7 and have implemented the new Verification feature for users email. if i put ->middleware('verified'); on to a route, sure enough, the verification shows, and the user gets the option to resend the verification email.

However, i'd like that to send upon registration (it's not doing that now). It would be nice to send some kind of Welcome email, that would include the verification link.

Any ideas?

Thanks

14 Oct
9 months ago

elliotk left a reply on Laravel Architecture Howto

thanks @Snapey i was really hoping for something elegant, but clearly there isn't a solution. I'll take a look at what you did.

elliotk started a new conversation Laravel Architecture Howto

I am a bit stuck and need some architecture advice.

I am using the following theme package in my app, which allows users to set a theme of their choice.

https://github.com/igaster/laravel-theme

At the moment, the theme choice is set via a Settings model. This and other settings are retrieved and cached via the AppServiceProvider. All this is working fine.

    public function boot()
    {   
        $settings = \Cache::rememberForever('settings', function () {
                return Setting::all();
            });

        if (isset($settings->theme)) {
            if (Theme::exists($settings->theme)) {
                Theme::set($settings->theme);
            } else {
                Theme::set('default');
            }
        }
    }

However, I came across an issue installing the code for a new domain. Long story short, i believe that my app wouldn't install via Forge because the above was executing, when the migrations hadn't run, and the base tables were not present.

I then decided to move the above to a View composer instead, which allowed the app to install fine. However, i have now found, that the Theme doesn't return the correct (override) views, I presume because the view is already passed to the composer, by which point it's too late to alter it via the Theme setting.


    public function boot()
    {   

        View::composer(['*'], function ($view) {
            $settings = \Cache::rememberForever('settings', function () {
                return Setting::getAll();
            });

            if (isset($settings->theme)) {
                if (Theme::exists($settings->theme)) {
                    Theme::set($settings->theme);
                } else {
                    Theme::set('default');
                }
            }

            $view->with('settings', $settings);
        });
}

So my question is, how can I retrieve the users preferred theme from a Model, and pass it to the Theme package, without using a View Composer, but also in a way that allows migrations to run on a fresh install.

Thanks for any advice.

Elliot

13 Oct
9 months ago

elliotk left a reply on Installation Problem

Have you tried composer update?

08 Oct
9 months ago

elliotk left a reply on A New Open Source Package For Google Places Api.

@SachinAgarwal did you write this blog post? Keen to try your package.

28 Sep
9 months ago

elliotk started a new conversation W3C Validator - Flash - Vue

Hello,

Does anyone know how to fix this error on the W3C HTML Validator?

Element flash not allowed as child of element div in this context. (Suppressing further errors from this subtree.)

From my source:

'''

'''

Thanks

04 Sep
10 months ago

elliotk left a reply on JSON Decode Help

That was it, I'm getting what I need now, thanks a lot!

elliotk left a reply on JSON Decode Help

I do that already...

$bodyReceived = file_get_contents('php://input');
$json = json_decode($bodyReceived);

This then allows me to do $json->id and other, let's say parent level items, but i can't get to the child objects / arrays.

elliotk left a reply on JSON Decode Help

Thanks @aurawindsurfing but it's not working...

Cannot use object of type stdClass as array

elliotk started a new conversation JSON Decode Help

Hello,

I'm getting data from PayPal which I am converting to JSON.

$bodyReceived = file_get_contents('php://input');
$json = json_decode($bodyReceived);

I'm able to access $json->id and $json->resource_type but I am not sure how I can access any objects that are in their own arrays for example $json->resource->state

Can someone help me understand how best to process and access the data? Below is a sample of what comes from PayPal.

array (
  'id' => 'WH-3JG8044908997094X-31F55277P94300413',
  'event_version' => '1.0',
  'create_time' => '2018-09-04T13:15:45.561Z',
  'resource_type' => 'sale',
  'event_type' => 'PAYMENT.SALE.PENDING',
  'summary' => 'Payment pending for $ 0.01 USD',
  'resource' => 
  array (
    'id' => '7TN57446DV952442R',
    'state' => 'pending',
    'amount' => 
    array (
      'total' => '0.01',
      'currency' => 'USD',
      'details' => 
      array (
        'subtotal' => '0.01',
      ),
    ),
    'payment_mode' => 'INSTANT_TRANSFER',
    'reason_code' => 'RECEIVING_PREFERENCE_MANDATES_MANUAL_ACTION',
    'protection_eligibility' => 'ELIGIBLE',
    'protection_eligibility_type' => 'ITEM_NOT_RECEIVED_ELIGIBLE,UNAUTHORIZED_PAYMENT_ELIGIBLE',
    'invoice_number' => '',
    'custom' => '90048630024435',
    'parent_payment' => 'PAY-6HU3694398562973HLOHIK2I',
    'create_time' => '2018-09-04T13:15:37Z',
    'update_time' => '2018-09-04T13:15:37Z',
    'links' => 
    array (
      0 => 
      array (
        'href' => 'https://api.sandbox.paypal.com/v1/payments/sale/7TN57446DV952442R',
        'rel' => 'self',
        'method' => 'GET',
      ),
      1 => 
      array (
        'href' => 'https://api.sandbox.paypal.com/v1/payments/sale/7TN57446DV952442R/refund',
        'rel' => 'refund',
        'method' => 'POST',
      ),
      2 => 
      array (
        'href' => 'https://api.sandbox.paypal.com/v1/payments/payment/PAY-6HU3694398562973HLOHIK2I',
        'rel' => 'parent_payment',
        'method' => 'GET',
      ),
    ),
  ),
  'links' => 
  array (
    0 => 
    array (
      'href' => 'https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-3JG8044908997094X-31F55277P94300413',
      'rel' => 'self',
      'method' => 'GET',
    ),
    1 => 
    array (
      'href' => 'https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-3JG8044908997094X-31F55277P94300413/resend',
      'rel' => 'resend',
      'method' => 'POST',
    ),
  ),
)
20 Aug
10 months ago

elliotk left a reply on Updating Pivot Attributes

thanks @tykus sorry, i'm new to the pivots, could you be a little more specific for me?

elliotk started a new conversation Updating Pivot Attributes

Hello,

I have a Cart model and a Product model, which i pivot together through a many to many relationship. On the pivot, I have an additional column, quantity, which stores the quantity of the product added to the cart.

If a user adds the same product again, I want to increment the pivot quantity.

On the Cart model I have the relationship defined properly.

return $this->belongsToMany('App\Product')->withPivot('quantity');

In my CartController, I get the current cart in $cart and I have the incoming product_id in the $request. I loop the current cart items, checking whether the product exists in the cart. If found, I want to increment the current quantity with the additional quantity passed on the request. I've written the below, it doesn't throw any errors, but it's not working.

        foreach ($cart->products as $product) {
            if ($product->id == $request->product_id) {
                $product->pivot->quantity = $product->pivot->quantity + $request->quantity;
                $product->save();
                return redirect('/cart');
            }
        }

Can anyone please explain how to update the pivot attributes properly?

Thanks

24 Jul
11 months ago

elliotk left a reply on Categories, Products And Routing

Can anyone provide any guidance on this?

Thanks

20 Jul
11 months ago

elliotk started a new conversation Categories, Products And Routing

Ok guys, here's the thing....

I've created a model for Categories which works nicely with Sub Categories (from an Eloquent perspective)

Cat 1 Cat 1 -> Sub 1 Cat 1 -> Sub 1 -> Sub 2 Cat 1 -> Sub 1 -> Sub 2 -> Sub 3

I really don't want to limit the depth unless I have to.

I then have a Product Model, and any given Product can be associated to any level of category, I had in mind that a Product would be placed in the lowest category, and roll up, but I may have it so that it needs to be placed at every level - we'll see.

URL's will look like this (all driven on slugs)

/cat1/sub2/sub3/product-name /cat3/product-name /cat1/sub2/product-name

So a few questions

  1. How do you handle N depth of category in the route?
  2. How then do you determine whether a given route is a Product or a Category?

I'm considering some kind of centralised slug management, which allows unique slugs and determines the correct controller to hand off to. Seems complex.

Part of me things I should just do

/cat1 /sub2 (which is really /cat1/sub2) /sub3/product-name

eg {category} {category}/{product}

I just feel, for nested categories, you lose some readability if the categories don't stack in the address bar and tell a story?

I welcome all and any feedback.

05 Jan
1 year ago

elliotk left a reply on Arbitrary Data Points

The simple solutions are the best

protected $statuses = [
        ["name" => "Draft", "value" => "1"],
        ["name" => "Published", "value" => "2"]
    ];
04 Jan
1 year ago

elliotk left a reply on Arbitrary Data Points

In your example @lostdreamer_nl how would I add further data to the statuses. For example

status_id = 1, value = 1, text = Draft, valid = true;

I’d probably want something like this for the different statuses I’d have.

elliotk left a reply on Form For Create And Update - Duplication

Thanks @Talinon that's just what I was looking for!

elliotk left a reply on Form For Create And Update - Duplication

I looked at this, wasn't in favour due to the extra overheads. Is there a more simplistic approach?

elliotk started a new conversation Form For Create And Update - Duplication

Hello,

I have a form for Create and a form for Update/Edit. It seems to me, that most of the logic is the same. Yet I have a lot of repetition of HTML.

The only differences I see are

  1. The Form Action - Create and Update have different URLs
  2. The Value on Form Inputs are populated differently.

Create <input type="text" class="form-control {{ $errors->has('title') ? ' is-invalid' : '' }}" name="title" id="title" value="{{ old('title') }}" placeholder="Title" required>

Update <input type="text" class="form-control {{ $errors->has('title') ? ' is-invalid' : '' }}" name="title" id="title" value="{{ $post->title }}" placeholder="Title" required>

The rest is pretty much the same. Right now, I have 2 files, with 90% the same code, I'd really like to have one file, so it's more maintainable.

I'd be really interested to hear how others handle this.

Thanks

31 Dec
1 year ago

elliotk left a reply on Handling Exceptions

Solution here: https://github.com/jrean/laravel-user-verification/issues/128

Needed to add:

use Jrean\UserVerification\Exceptions\UserNotVerifiedException; 

elliotk started a new conversation Handling Exceptions

Hello,

I am trying to display a custom error page for a particular exception generated by this package: https://github.com/jrean/laravel-user-verification

It's to indicate that the current user is not verified.

I've updated the Exception Handler as follows:

    public function render($request, Exception $exception)
    {
        if ($exception instanceof UserNotVerifiedException) {
            return response()->view('errors.not-verified', [], 500);
        }
        return parent::render($request, $exception);
    }

If I dd($exception) I get the below, so I am presuming I have the syntax correct.

UserNotVerifiedException {#278 ▼
  #message: "This user is not verified."
  #code: 0
  #file: "/Users/elliot.knight/Code/cms/vendor/jrean/laravel-user-verification/src/Middleware/IsVerified.php"
  #line: 26
  trace: {▶}
}

However, no matter what I try, I get the generic exception shown.

Any help would be appreciated.

Thanks

Elliot

29 Dec
1 year ago

elliotk left a reply on Arbitrary Data Points

Thanks @lostdreamer_nl that's really helpful advice. For now only a developer could add a status, so I'll follow your example.

28 Dec
1 year ago

elliotk started a new conversation Arbitrary Data Points

Hello,

I have a posts table containing blog posts. I'd like to add some new functionality for example post status (draft / in review / published) and visibility (everyone / logged in users / admin users). I was just going to add 2 columns to my post table, and use integer to identify the current value (eg 0 draft / 1 in review / 2 published).

However, I am wondering, should I create a new table for status and a new table for visibility so that I can have these options stored in the database with also a description of each one and perhaps some other data points?

Should I create a model for this eg PostStatus and PostVisibility or is that overkill?

Any thoughts on handling arbitrary data would be helpful.

Thanks

25 Nov
1 year ago

elliotk left a reply on Help Submitting Form

@BryceSharp great idea. Done and working. Sometimes the simple solutions are not obvious! Thanks for that.

For anyone who is interested, I pass "data-act" which is the form action data, and use JavaScript to replace that on the modal on load.

<button type="button" 
                                    class="btn btn-danger btn-sm" 
                                    data-toggle="modal" 
                                    data-target="#exampleModal" 
                                    data-act="/admin/tags/{{ $tag->slug }}" 
                                    data-type="tag" 
                                    data-str="{{ $tag->name }}">
                                        Delete
                                    </button>

JavaScript

<script>
  $('#exampleModal').on('show.bs.modal', function (event) {
    var button=$(event.relatedTarget) // get the button
    var modal = $(this) // get the modal form
    modal.find('.modal-body').text('Are you sure you want to delete the ' + button.data('type') + ': ' + button.data('str'));
    modal.find('#tag-delete-form').attr('action', button.data('act')); // set the modal body text to include button data
})
</script>