ollie_123

ollie_123

Member Since 9 Months Ago

Experience Points
17,080
Total
Experience

2,920 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
78
Lessons
Completed
Best Reply Awards
5
Best Reply
Awards
  • start your 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-in-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 Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist 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.

Level 4
17,080 XP
Oct
23
1 day ago
Activity icon

Replied to Property [product_id[]] Does Not Exist On The Quotes Component

Hey @laracoft

Sure thing:-

// ddd($qty_a);
array:2 [▼
  1 => "1"
  2 => "3"
]

/// ddd($product_id_a)
array:2 [▼
  0 => "1"
  1 => "2"
]
Oct
22
2 days ago
Activity icon

Replied to LiveWire: Passing Data From One Component To Another

Hi @randy_johnson

Normally if you're displaying data from the database you would call it inside of the render() method.

If you're passing data from one component to another then you would call it inside of the mount() function on the 2nd component

For example

//Component A (Customers)

public function render()
    {
        $customers = Customer::count();
        return view('livewire.customers', compact( 'customers'));
    }

If you wanted to link to a customer record you would still use your normal route model binding in web.php and in your anchor tag in your blade & use something like: <a href="{{ route('view-customer', $customer->uuid) }}"....

Then in your 2nd component you would call the mount method and bind the data to the relevant values

// Component B (View Customer)

public $name, $age, $dob;

public function mount($uuid)
{
    $customer = Customer::where('uuid', $uuid)->first();
        $this->name  = $customer->name;
        $this->age   = $customer->age;
        $this->dob   = $customer->dob;
}

Then you can call the variables in your blade like normal {{ $name ))

In regards to debugging, laravel will still throw up error exceptions however if you're not getting any error exceptions, the network tab in dev tools is a good place to look.

Activity icon

Replied to Property [product_id[]] Does Not Exist On The Quotes Component

Hey @laracoft thats great thank you. That now submits, however the only problem thereafter is i get an array to string conversion error on inserting into the product_quote pivot table. Both models have a many to many relationship to eachother.

$products = Product::whereIn('id', $this->product_id_a)->get();
$products = $products->mapWithKeys(function($product) {
    return 
    [
        $product->id => [
            'product_sale' => $product->sale, 
            'product_cost' => $product->cost, 
            'qty'          => $this->qty_a],
    ];})->all();
$newQuote = Quote::create($quote_data);
$newQuote->products()->attach($products);

I've tried moving $this->qty outside of the $product->id => array but then it gives an error of qty cant be null.

Thank you in advance.

Activity icon

Replied to Property [product_id[]] Does Not Exist On The Quotes Component

Hey @laracoft

Thanks for the suggestion, i tried

//LW Component
public $qty_a = [];
public $product_id_a = [];

//View
<td><input type="checkbox" wire:model.lazy="product_id_a"></td>
<td><input type="number" wire:model.lazy="qty_a"></td>

but the removal of [] in wire:model... then causes every checkbox to be checked when i select a single checkbox?

Activity icon

Replied to Property [product_id[]] Does Not Exist On The Quotes Component

Hi @laracoft

Ah awesome, here's the rest of the table:-

<tbody class="text-sm">
@forelse($products as $product)
    <tr class="mx-auto border border-gray-300 overflow-hidden">
        <td class="px-4 py-3"><i class="dripicons-box"></i></td>
        <td class="px-4 py-3 ">{{ $product->brands->name }}</td>
        <td class="px-4 py-3 ">{{ $product->code }}</td>
        <td class="px-4 py-3">{{ $product->description}}</td>
        <td class="px-4 py-3 hidden-mobile">£{{ number_format($product->sale, 2) }}</td>
        <td class="px-4 py-3 hidden-mobile">{{ $product->taxes->rate }}</td>
        <td class="px-4 py-3 hidden-mobile">{{ $product->status}}</td>
        <td class="px-4 py-3 "><input type="checkbox" class="w-5 h-5" wire:model.lazy="product_id[]"></td>
        <td><input type="number" wire:model.lazy="qty"></td>
    </tr>
@empty 
<small>No Products</small>
@endforelse
</tbody>
Activity icon

Started a new Conversation Property [product_id[]] Does Not Exist On The Quotes Component

Evening All

I'm getting the above error and i'm unsure on the best way to go about this. I have a table where a user can select products with a checkbox and also insert the qty required. So i defined the variables in my LW controller as such :-

public $qty = [];
public $product_id = [];

& in my LW view component i have

//Table....

<td ><input type="checkbox" wire:model.lazy="product_id[]"></td>
<td><input type="number" wire:model.lazy="qty[]" placeholder="0"></td>

But when i select the checkbox i get the error above.

If i change the input from wire:model.lazy="product_id[]" to wire:model.lazy="product_id" when i select a checkbox it then selects all of them. Same with the qty field.

Please can someone advise on where i might be going wrong?

Thank you in advance.

Activity icon

Awarded Best Reply on Livewire Component Not Found

Hi @randy_johnson

It looks as though you're calling show-admins but your Livewire component is called Admin.

You either need to change your Livewire component name to class ShowAdmins along with the file name or change the href & route to match your existing component.

Oct
21
3 days ago
Activity icon

Replied to How Do I Get The Current Date In This Format Wednesday 26 Aug

Hey @tomasosho

You could use carbon for this and do something like:-

use Carbon\Carbon;

$d = '2020/08/26'; // Your date from database...
$day = Carbon::parse($d)->format('l m F');

Which will show: Wednesday 08 August

Activity icon

Replied to Livewire Component Not Found

Hi @randy_johnson

It looks as though you're calling show-admins but your Livewire component is called Admin.

You either need to change your Livewire component name to class ShowAdmins along with the file name or change the href & route to match your existing component.

Oct
20
4 days ago
Activity icon

Replied to Livewire Not Making Any Ajax Requests?

Legend as always.

Thanks @snapey.

Activity icon

Replied to Livewire Not Making Any Ajax Requests?

Hey @snapey, i've checked and its the uuid inside of the wire:click field as expected. Eg fb189fa1-f8b6-4603-8f23-4618d503ebca. I'm guessing the hyphens are illegal characters in the wire:click action?

Activity icon

Replied to Mail/notification Sending Error

Have you checked that the .env file matches your config mail.php file?

Can you share the mail section of your .env file?

Activity icon

Replied to Need Help With CRUD & Ajax

Once you've got the basics down with the Laravel From Scratch video series you could look at using Livewire as this offers a really nice way to make ajax requests.

Activity icon

Replied to How Do I Register The System Date?

In your model make sure you use protected $dates = ['registered_at'];. Then in your blade file you can grab the date from the array and format it such as $news->registered_at->format('d/m/y');

Activity icon

Replied to Auth::user() Versus Auth::User->select('id', 'name')->get()

Hi @tedeumf

Whilst the subject is similar, you should really start your own thread with that question as this thread has been solved & closed. However for your question, if you include a user_id on the students table you can then call the required data where the user_id matches the authorised user. Something like

$studentData = \App\Models\Student::where('user_id', Auth::user()->id)->get() 
//or ->first() depending on what you're looking to do.
Activity icon

Replied to Livewire Not Making Any Ajax Requests?

Hey @snapey @adityar15. Mine is resolved, there was a stray </div> before the form which was causing the issue.

On a side note, whats the best way of passing a uuid via a wire:click='complete({{$task->uuid}})' as currently i get Uncaught SyntaxError: Invalid or unexpected token in the console. Whereas if i use ID it works just fine.

Oct
18
6 days ago
Activity icon

Replied to Livewire Not Making Any Ajax Requests?

Hey @snapey, Yep have checked and there are no errors in the console.

Activity icon

Replied to Livewire Not Making Any Ajax Requests?

Hey @snapey

The whole component gets rendered, its just table displaying the data. Its the add customer component within the page that isnt making any ajax requests or firing back with any validation errors.

Normally in the network tab after moving to the next input field my wire:model.lazy will fire a request. But currently i'm getting nothing and no validation errors on the store method.

I included the header tag as thats what we were discussing yesterday on another thread to do away with the blade view file and call the header directly from the component.

UPDATE: The search function is working and making network requests on the page and displaying results, its just the add component that seems to not be working anymore.

 <form class="w-full max-w-sm">
...
    <button wire:click.prevent="store()">Add</button>
</form>  
Activity icon

Started a new Conversation Livewire Not Making Any Ajax Requests?

Evening All

I'm completely stumped, my customers page was working perfectly and could add customers etc via the livewire controller component but now i cant see any network requests going through.

My livewire view file has...

<div>
    <x-slot name="header">
        <h2 class="text-xl inline mt-3">{{ __('Customers') }}</h2>
     </x-slot>

...

My Route is Route::get('customers' , ShowCustomers::class)->name('customers');

Its almost as if its not seeing the layouts.app file and not making any ajax requests. I've gone through my git changes and i cant see anything major that would prevent this page from making any requests. I've checked another page with a very similar setup just different data and its working fine.

Please could someone advise where i might be going wrong or where to look to debug as the log file doesnt show any errors (and yes i have errors turned on).

Thanks in advance.

Oct
17
1 week ago
Activity icon

Replied to Livewire - Passing Data To View & Component

Hey @snapey

Apologies, i didnt update my parameter name in the OP, i tested with ID then switched and updated everything to uuid.

Removing x-app-layout and creating the div with x-slot.. worked a charm.

Really appreciate your help. Thank you :)

Also @vengiss thank you for your message, it was a routing issue i think i had as removing the public property didnt change the error.

Activity icon

Replied to Livewire - Passing Data To View & Component

Hey @snapey

My link is <a href="{{ route('view-customer', $customer->uuid) }}"...

My Route is

Route::get('view-customer/{uuid}' , App\Http\Livewire\Tenant\ViewCustomer::class)->name('view-customer');
Activity icon

Replied to Livewire - Passing Data To View & Component

Thanks @vengiss much appreciated.

For some reason it then throws Undefined variable: header in my layouts.app file but this works on every other page.

I'm using L8 & tailwind and have my standard view-customer.blade file with the @livewire component included.

<x-app-layout>
    <x-slot name="header">
        <h2 class="font-bold text-xl uppercase text-gray-800 leading-tight py-0">
            {{ __('View Customer') }}
        </h2>
        
    </x-slot>


    <div class="py-8">
        @livewire('tenant.view-customer')
    </div>
</x-app-layout>

But if i remove {{ $header }} from the layouts.app file then the view-customer page then works?

Is there a better way of doing this without using blade files that then include a livewire component?

Thanks again.

Activity icon

Started a new Conversation Livewire - Passing Data To View & Component

Hi All

I'm pretty new to livewire & i'm a but stuck trying to pass data to the Livewire component to a view-customer page. I read in the livewire docs that you pass the id via route model binding same as Laravel and then mount the data inside of the component however i'm getting an error of Unable to resolve dependency [Parameter #0 [ <required> $id ]] in class App\Http\Livewire\Tenant\ViewCustomer.

class ViewCustomer...

{
    public $name;
    public $email;
    public $customer;

    public function mount($id)
    {
        $contact = Customer::find($id);

        $this->name = $contact->name;
        $this->email = $contact->email;
    }

and my link is <a href="{{ route('view-customer', $ViewCustomer->id) }}"

Any advice would be greatly appreciated.

Sep
25
4 weeks ago
Activity icon

Replied to Query Data From Through Pivot Table Based On Slug

Hi @twg_

You need to add ->get() to your method and a return.

public function getBooksByCategory($slug)
{
	$books = Book::with('related')
	->whereHas('categories', function ($query) use ($slug) {
	$query->where('category.slug', $slug)->get();
		});
	return $books;
}
Activity icon

Replied to Best Way To Get Datetime-local Current Time...

Hi @snapey

Here's the code for the input:

<label>Start</label>
 <input required  value="2020-10-01T12:00" type="datetime-local" maxlength="30" name="start" class="form-control">

I tried passing a formatted date from the controller to get the current time

$dateTimeNow = Carbon::now()->format('y-m-d'.'T'.'H:i');

but still no joy.

@kingmaker_bgp thanks for the advice however its not the validation thats failing in the controller its the datetime-local field that doesnt recognise the input and prevents form submit.

@jlrdw again, i don't have an issue storing the date, i convert in the controller. Its the submitting of the form that is the issue where the datetime-local input is clashing with the date inputted by the user. However as previosuly mentioned if i use value="2020-09-20T21:00" the user can select a date and i can submit. i'm just trying to get the current date & time to save starting in Sept.

Thanks all.

Sep
24
1 month ago
Activity icon

Replied to Best Way To Get Datetime-local Current Time...

Hey @jlrdw

Thanks for the advice however its not the storing i have an issue with the formatting of the datetime of the input field.

If i don't set a default value whatever date i pick it wont allow me to submit. Currently i have to set the default value as value="2020-09-20T21:00" which obviously isn't ideal as its never the current date.

Activity icon

Started a new Conversation Stuck Trying To Update Pivot Table With Role_id

Evening All.

I'm trying to update a pivot table with a role_id of a user but it keeps returning an error of Collection::roles does not exist.

I've read the docs multiple times and im struggling to see what i'm missing. My user model has

public function roles()
   {
       return $this->belongsToMany('\App\Role');
   }

and my role model has

public function users()
    {
        return $this->belongsToMany('\App\User');
    }

In the controller i have

$user = \App\User::find($id);
$user->roles()->updateExistingPivot(['user_id' => $id, 'role_id' => $request->role_id]);

but keep getting the error. I'm pretty sure its something obvious that i'm missing but i've been staring at it too long to see.

Please can someone advise where i'm going wrong.

Thank you in advance.

Sep
20
1 month ago
Activity icon

Started a new Conversation Best Way To Get Datetime-local Current Time...

Hi All

I'm working on an app that has a datetime-local input and i'm trying to work out the best way to get the current date & time and to format it as eg 2020-09-20T21:00.

If its not formatted this way, i cant submit the form and it keeps bouncing me back to input a date as it doesn't recognise the date inputted from the datetime-local field.

Any advice would be greatly appreciated.

Thanks in advance.

Sep
10
1 month ago
Activity icon

Replied to New To Vue - Stuck On Axios.delete

Awesome thanks @bobbybouwmann much appreciated.

Sep
09
1 month ago
Activity icon

Replied to New To Vue - Stuck On Axios.delete

Hey @bobbybouwmann thank you for the tip. Much appreciated. I have removed id from the task object.

I tried to print the data but still got no id's, i then realised that i hadn't declared it in the TaskResource... doh!.

Its now deleting as expected. :)

Thank you for your help.

Side note, in vscode i get a "Problem" of 'index' is defined but never used on this line

<li class="list-group-item" v-for="(task, index) in list" :key="task.id">

Is there a better way of doing this?

Activity icon

Replied to New To Vue - Stuck On Axios.delete

Hey @bobbybouwmann, i think you could be right. Could it be that i'm binding the id to the task which then the button can't obtain the id?

<li v-for="(task, index) in list" :key="task.id"> {{ task.name }} 
     <button @click="deleteTask(task.id)" class="btn btn-danger btn-xs pull-right">Delete</button>
 </li>

Currently this is how i have the methods set for fetching, creating & deleting tasks:-

export default {
        data() {
            return {
                list: [],
                task: {
                    id: '',
                    name: '',
                    description: ''
                }
            };
        },
        
        created() {
            this.fetchTaskList();
        },
        
        methods: {
            fetchTaskList() {
                axios.get('api/tasks').then((response) => {
                    this.list = response.data.data;
                });
            },
 
            createTask() {
                axios.post('api/tasks', this.task)
                    .then((res) => {
                        this.task.name = '';
                        this.task.description = '';
                        this.edit = false;
                        this.fetchTaskList();
                    })
                    .catch((err) => console.error(err));
            },
 
            deleteTask(id) {
                axios.delete('api/tasks/' + id)
                    .then((response) => {
                        this.fetchTaskList()
                    })
                    .catch((err) => console.error(err));
            },
        }
    }

Thanks in advance.

Activity icon

Started a new Conversation New To Vue - Stuck On Axios.delete

Evening all

I decided to dip my toes into Vue and have been playing with a simple task list to get my head round components & CRUD in Vue etc.

So far i can add a task and append it to the list however i'm a bit stuck on the delete method as i keep getting an error of api/tasks/undefined 404 message: "No query results for model [App\Task] undefined".

Please could someone advise where im going wrong.

//my-tasks Component
<h4>All Tasks</h4>
                <ul class="list-group">
                    <li v-if='list.length === 0'>There are no tasks yet!</li>
                    <li class="list-group-item" v-for="(task, index) in list" :key="task.id"> {{ task.name }} - {{ task.description }} 
                        <button @click="deleteTask(task.id)" class="btn btn-danger btn-xs pull-right">Delete</button>
                    </li>
                </ul>

	    deleteTask(id) {
                axios.delete('api/tasks/' + id)
                    .then((response) => {
                        this.fetchTaskList()
                    })
                    .catch((err) => console.error(err));
            },

// Controller 
public function destroy($id)
    {
        $task = Task::findOrFail($id);
        $task->delete();
        return response()->json("deleted");
    }

Thanks in advance.

Aug
30
1 month ago
Activity icon

Replied to Inserting Into Line_items Table Issue

Thanks @sinnbeck & @snapey much appreciated.

Activity icon

Replied to Calculating Totals In Model

Thanks @povilaskorop much appreciated.

Aug
29
1 month ago
Activity icon

Replied to Inserting Into Line_items Table Issue

@snapey you're a legend as always.

Thanks for your help, that was exactly what i was looking to do.

Activity icon

Replied to Inserting Into Line_items Table Issue

Hey @snapey

You're absolutely right, not sure how i missed that.

This is what i had on a previous attempt...

	//Update status in orders table
        $orderComplete = \App\Order::where('uuid', $request->uuid)->first(); 
	\App\Order::where('uuid', $orderComplete->uuid)->update(['Status' => '2', 'completed_at' => Carbon::now()]);
	//event(new........

	//get details from order an insert into invoice table
	$invoice_data = array(....);
        $invoice = \App\Invoice::create($invoice_data);

	//get product details from order and insert into invoice_line_items with invoice_id
        $products = \App\Product::whereIn('id', $orderComplete->products->product_id)->get();
        $invoice_line_items = array(
            'invoice_id'    => $invoice->id,
            'prod_name'     => $products->name,
            'prod_desc'     => $products->description,
            'prod_sale'     => $products->sale,
        );
        \App\InvoiceLineItems::create($invoice_line_items);

but get Property [product_id] does not exist on this collection instance.

Essentially, when an order is set to complete, the order uuid is passed to the controller, the orders table is updated to complete, then the details from the orders table is inserted into the invoice table.

The invoice_line_items table takes the products related to the order and inserts them into the ``invoice_line_items``` table.

In regards to relationships, the orders and products tables have a many to many relationship both ways and a pivot table between them order_product.

I'm just having difficulty obtaining the product data through the relationship.

If i ddd($orderComplete->products) i can see the products for that order but cant access them in my query for some reason.

Thank you in advance.

Aug
28
1 month ago
Activity icon

Replied to Inserting Into Line_items Table Issue

Hey @jlrdw

Thanks for the suggestion, i get what you're saying however i'm struggling to get the product info from that line.

$products = \App\Product::whereIn('id', request()->orderComplete->product_id)->get(); 

// ^ Gives error trying to get property of product_id non object

$products = \App\Product::whereIn('id', request()->orderComplete->products->product_id)->get(); 

// ^ Gives error of trying to get property of products non object

The relationships are as follows Products belongsToMany App\Order Order belongsToMany App\Product order_product pivot table between them.

Activity icon

Replied to Inserting Into Line_items Table Issue

HI @jlrdw thanks for your response, i believe your suggesting how to display the data in the view.

The issue i have is when an order is completed, i'm trying to create an invoice using the order data which works fine and update the invoice_line_items table with the products & their info but struggling to obtain the product info as i get errors of trying to get property.... of non object.

Sorry if i'm missing something.

Activity icon

Started a new Conversation Inserting Into Line_items Table Issue

Evening all,

I'm trying to insert data into 2 tables when an order has been completed. Table one is the invoice table which takes the order ref, who its assigned to etc Table two is the invoice_line_items table which takes all of the product info and costs etc.

The issue i'm having is obtaining the data to insert into the invoice_line_items table. The data is being pulled from the orders table and inserted into the invoice table, then the products (that belong to orders via a many to many pivot table) are to be inserted into the invoice_line_items table along with the invoice id.

I've tried getting all products and putting them into a mapWithKeys function but that doesnt allow me to pull the invoice_id as its inside of the products array.

Here's where i'm currently at

$orderComplete = \App\Order::where('uuid', $request->uuid)->first(); 
$invoice_data = array(
            'uuid'          => (string) \Str::uuid(),
            'order_id'      => $orderComplete->id,
            'customer_id'   => $orderComplete->customer_id,
            'ref'           => $orderComplete->ref,
            'assigned_to'   => $orderComplete->assigned_to
        );
        $invoice = \App\Invoice::create($invoice_data);

// $products = \App\Product::whereIn('id', request()->orderComplete->product_id)->get(); gives error trying to get property of product_id non object

// $products = \App\Product::whereIn('id', request()->orderComplete->products->product_id)->get(); gives error of trying to get property of products non object

$products = \App\Product::whereIn('id', request()->orderComplete->product_id)->get();
        $invoice_line_items = array(
            'invoice_id'    => $invoice->id,
            'prod_name'     => $products->name,
            'prod_desc'     => $products->description,
            'prod_cost'     => $products->cost,
            'prod_sale'     => $products->sale,
        );
        \App\InvoiceLineItems::create($invoice_line_items);

Please can someone advise where i might be going wrong.

Thank you in advance

Aug
27
1 month ago
Activity icon

Replied to Calculating Totals In Model

Hey @sinnbeck.

Sorry if i'm missing something but what you posted is what i currently have which is giving me the error Property [name] does not exist on this collection instance

Can i not loop over the products in an array like the following?

$products = \App\Product::whereIn('id', request()->product_id)->get();

$orderLineItems = array(
            'order_id'      => $newOrder->id,
            'prod_name'     => $products->name, //Property [name] does not exist on this collection instance
            'prod_desc'     => $products->description,
            'prod_cost'     => $products->cost,
            'prod_sale'     => $products->sale,
	     //Plus vat calculations etc...
        );

        \App\OrderLineItems::create($orderLineItems); 

Again my apologies if i'm missing something obvious.

Thank you in advance.

Activity icon

Replied to Calculating Totals In Model

Thanks @martinbean. I appreciate the advice. It makes a lot of sense.

Im just trying to implement it in now but having a bit of trouble with an error of Property [name] does not exist on this collection instance when trying to pull the product name, price etc... Which i'm a but confused about as if i do a ddd($products) i can see the attributes in an array.

$order = array(
            'uuid'          => (string) \Str::uuid(),
            'ref'           => request()->ref,
            'assigned_to'   => request()->assigned_to,
            'customer_id'   => $customerId,
);

$newOrder = \App\Order::create($order);

// Pull product id's from the order form
$products = \App\Product::whereIn('id', request()->product_id)->get();

$orderLineItems = array(
            'order_id'      => $newOrder->id,
            'prod_name'     => $products->name, //Property [name] does not exist on this collection instance
            'prod_desc'     => $products->description,
            'prod_cost'     => $products->cost,
            'prod_sale'     => $products->sale,
	     //Plus vat calculations etc...
        );

        \App\OrderLineItems::create($orderLineItems); 

If you could advise where i might be going wrong it would be much appreciated.

Activity icon

Replied to Calculating Totals In Model

Thanks @martinbean thats really good advice. I’ll get that implemented ASAP.

I guess that I should really do the same for the order aswell then rather than having a pivot table of order_product because as you say, if a user deletes a product or updates the price it will affect the order.

Aug
26
1 month ago
Activity icon

Replied to Calculating Totals In Model

Hey @martinbean, thank you for the suggestion. Thats a really good point. Currently, i have an order table and products table with a many to many relationship and the order_id & product_id's being stored via a pivot table.

Lets say that upon creating an invoice a new row is inserted into an Invoice table, how would i account for multiple products as it could range from 1 - 15+ products. Would it be a case of an invoices table & invoice_products table with a belongsTo on the invoice_products & hasMany on the invoice table?

//invoices return $this->hasMany('App\InvoiceProduct');
-id
-order_id
-payment_ref
-etc....

//invoice_product return $this->belongsTo('App\Invoices');
-id
-invoice_id
-product_name
-product_description
-sale_net
-vat_rate
-sale_inc_vat
-etc
Aug
25
1 month ago
Activity icon

Replied to Calculating Totals In Model

@sinnbeck you are an absolute legend thank you. Much appreciated. :)

Activity icon

Replied to Calculating Totals In Model

Hey @sinnbeck thanks for your response. That suggestion does work if i was only using one vat rate. Unfortunately though the vat rate can change depending on the product or service.

In my products table i have

-id
-name
-vat_id
-cost
-sale

I then have a jobs table and a pivot between job & products via job_product

In my VAT table i have

-id
-calc (0, 1.05 or 1.2)
-rate (0%, 5% or 20%)
-description

Thank you in advance.

Activity icon

Started a new Conversation Calculating Totals In Model

Afternoon All, i hope you're all well?

I'm trying to calculate the total invoice value including the vat amount and am getting a bit stuck. I think i've been staring at it too long to see it clearly anymore.

I have 3 functions in the job model.

getTotalSaleAttribute gathers the total sale price (net) for all products relating to that order.

getTotalVatAttribute which is fine. This just takes away the total price (inc vat) from the vat amount.

getTotalSaleIncVatAttribute gathers the total sale price (net) for all products relating to that order & heres the bit that i'm getting stuck on, pulls the vat rate calculation and times's the net sale total by the vat rate.

The product table has the vat_id from the VAT table as it belongs to VAT, and the VAT table has the calc column which would be 1.2 (20%).

// Products belongsTo VAT
// Vat hasMany Products

public function getTotalSaleIncVatAttribute()
    {
        $total = 0;
        $vat = 0;
        // $vat = $this->products->vat->calc; 
	// Currently this gives ^ an error of Property [vat] does not exist on this collection instance

        // Total net price of products related to the order
        $total += $this->products->sum(function($product) {
            return $product->sale;
        });

	// Total price of products related to the order times by the vat rate
        return $total * $vat;
    }

Hopefully it makes sense lol. Please could someone advise on where i might be going wrong?

Thank you in advance.

Aug
15
2 months ago
Activity icon

Replied to Odd Things Happening With Ajax Search

Awesome thank you @Sinnbeck. Much appreciated.

Activity icon

Started a new Conversation Odd Things Happening With Ajax Search

Morning All

I've got an Ajax search working but there are some odd things happening when i search.

Thing No1: When i search the result appears, but if i clear the result by deleting the characters in the search bar it keeps the result in the view when i would like it to disappear.

Thing No2: How would i delay the search by 200ms to stop the ajax firing every time a letter is typed?

        <input type="text" class="form-control fixed-element" placeholder="Search Customers..." name="search" id="search">

    <script type="text/javascript">
        $('#search').on('keyup',function(){
            $value=$(this).val();
                $.ajax({
                type : 'get',
                url : '{{URL::to('search')}}',
                data:{'search':$value},
                success:function(data){
                    $('#cardSearch').html(data);
                }
            });
        })
    </script>

```

Thank you in advance.
Aug
14
2 months ago
Activity icon

Replied to Ajax Search Shows In Console But Not In View?

hey @mbryson91, damn, i knew it would be simple thank you. Now working.

Side note...Is there a way to clear the search as when i delete characters in the input field it still populates the view with other customers. i.e the search see's "ad" and it shows adam, adrian etc... Im not sure if its best to clear the search or delay the search for 200ms or something along those lines?

Thanks in advance.

Activity icon

Started a new Conversation Ajax Search Shows In Console But Not In View?

Evening All

I'm trying to create an ajax search function to search customers. I can see the data being logged to the console but cant see it in the view? I'll be honest my JS knowledge isnt that great so forgive me if i'm missing something obvious.

Please could someone advise where i might be going wrong...

//Controller
public function search(Request $request)
    {
        if($request->ajax())
        {
            $output="";
            $customers=\App\Customer::where('name_first','LIKE','%'.$request->search."%")->get();
            if($customers)
            {
                foreach ($customers as $key => $customer) 
                {
                    $output.=

                    '<div class="card-body">
                        <h3>'. $customer->salutation . ' ' . $customer->name_first . ' ' . $customer->name_last .'</h3>
                    </div>';
                }
            return Response($output);
           }
        }
    }

//View

            <div id="cardSearch"></div> // Tried inside & outside the forelse loop...
        @forelse($customers as $customer)
        <div class="col-md-4">
            <div class="card-body">
                <h3>{{ $customer->salutation }} {{ $customer->name_first }} {{ $customer->name_last }}</h3>
            </div>
        </div>
        @empty
        <p>No Customers</p>
        @endforelse

<script type="text/javascript">
        $('#search').on('keyup',function(){
            $value=$(this).val();
                $.ajax({
                type : 'get',
                url : '{{URL::to('search')}}',
                data:{'search':$value},
                success:function(data){
                    $('cardSearch').html(data);
                    console.log(data);
                }
            });
        })
    </script>

I'm trying to essentially filter the cards to the result thats being searched.

Thank you in advance.