oli_d111

oli_d111

Member Since 1 Month Ago

Experience Points
5,440
Total
Experience

4,560 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
25
Lessons
Completed
Best Reply Awards
3
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.

Level 2
5,440 XP
Feb
21
2 days ago
Activity icon

Replied to Admin And User Login Pages

Glad it worked out.

Feb
20
3 days ago
Activity icon

Replied to Modal Delete Confirmation With BootstrapVue

Can you show us some code?

Is the data being pulled from a table? If so could you not pass the data to the modal such as ID so that you only require one modal for deleting multiple lines?

Without seeing your view & controller i'm going out on a limb but could you do something like:-

<a href="javascript:void(0)" id="delete" data-toggle="delete-modal" data-target="#delete-modal" data-id="{{ $yourvariable->id }}" class="yourButtonClass">Delete</a>
Activity icon

Replied to New Images Can't Be Found In Assets Folder, I Am Using Sass And Mix

Not done much with vue yet so could be well off base here but have you tried clearing the cache?

Also are you able to post some code to of the image url you're calling in your view file? or is it in your CSS?

Activity icon

Replied to Another Pivot Table Issue

Hey @ignium. I see what you're saying but the bit that confuses me is that i can see the products relevant to that order being called in the console. Also the number of products related to that order produces the same amount of undefined strings in the modal.

In my product model i've got

public function orders()
    {
        return $this->belongsToMany(Order::class);
    }

In the order model i've got

public function products()
   {
       return $this->belongsToMany(Product::class);
   }

& in the controller i've got

public function edit($id)
    {
        $where = array('id' => $id);
        $readAction  = Order::where($where)->first();
        $readAction->load('products');
        
        return Response::json($readAction);
    }

And just for good measure the script in the blade file



        $('#make').val(data.make);
        $('#mdl').val(data.mdl);
        $('#mdl_year').val(data.mdl_year);
        $('#engine').val(data.engine);
        $('#transmission').val(data.transmission);
        $('#products').val(data.products);
        console.log(data.products);

        let htmlString = createElements(data.products);  //Build HTML string with data.products
        $('#products').html(htmlString);  //Replace HTML of products div with the new HTML
        
        function createElements(arr) 
        {
            let elements = ''
            arr.forEach(function(el) 
            {
                elements += createDiv(el);
            })
            return elements
        }

        function createDiv(data) 
        {
            return `
            <div class="badge">
                <p>${data.products}</p>
            </div>
            `;
        }
    })
});
</script>

I'm sorry if I'm missing something super obvious.

Activity icon

Replied to Another Pivot Table Issue

Hey @ignium

Ah that makes sense, that was what i thought with the click event but wasn't 100% sure.

Thank you for this. I will look into sanitising aswell.

Out of curiosity, do you know what would cause the output to be undefined undefined undefined in the modal? I know that there are 3 products associated to this record but can't work out why its displaying as undefined?

Thanks in advance.

Feb
18
5 days ago
Activity icon

Replied to Another Pivot Table Issue

Hey @ignium.

Yeah, i was literally getting [object Object],[object Object],[object Object] back in the input field.

Awesome thank you for putting that together dude. Very kind of you. I'll admit, my JS knowledge isn't quite there yet so i'm trying to figure this out.

I'm just trying to wrap my head round it and modify to fit the call for products. In the modal, i have set the div id as products. And in the JS i have the following:-

<script>
  /* When click edit user */
  $('body').on('click', '#edit', function () {
      var readAction_id = $(this).data('id');
      $.get('readAction/' + readAction_id +'/edit', function (data) {
          $('#edit-modal').modal('show');
          $('#readAction_id').val(data.id);
          $('#make').val(data.make);
          $('#mdl').val(data.mdl);
          $('#mdl_year').val(data.mdl_year);
          $('#engine').val(data.engine);
          $('#transmission').val(data.transmission);
          $('#products').val(data.products);
          console.log(data.products);
        //   document.getElementById('products').innerHTML = products.toString();
        
        function createElements(arr) 
        {
            let elements = ''
            arr.forEach(function(el) {
            elements += createDiv(el);
            })
            return elements
        }
        function createDiv(data) 
        {
            return `
                <div class="badge-primary">
                <p>${data.products}</p>
                </div>
            `;
        }
        function click(event) 
        {
            event.preventDefault();
            // let elements = createElements(objects);
            document.getElementById('products').innerHTML = elements;
        }

      })
   });
</script>

However i think as its looking for a click event on the last function its not loading the data? Or am i missing something else?

Separately, in terms of XSS & sanitisation, would i still need to clean the inputs even if the user must be authenticated to access this page?

As always thank you in advance. I think i've moved from beer tokens to owing you a crate ;)

Feb
17
6 days ago
Activity icon

Replied to Another Pivot Table Issue

Hey @ignium.

Thank you for putting that together, i really appreciate it. I cloned the repo & had a look however its not quite what i'm looking to do. However a nugget of info i am taking is the @forelse. That is awesome. ;)

I feel like i'm so close to solving it. After reading around today i feel like i just need to decode the object and turn it into an array in the view.

I've tried a couple of different things but this is the furthest i've got:-

Modal Snippet:

<form method="post" action="{{ route('readAction.edit', $pending->id) }}">

            <div class="row">
                            <div class="col-sm-12">
                                <p>Optional Extras:</p>
                            </div><!-- end col -->
                            <div class="col-sm-12">
                            <input type="text" class="form-control" id="products">
                            </div>
                        </div><!-- end row -->

//Script Snippet... 

          $('#products').val(data.products);
          console.log(data.products);
          document.getElementById('products').innerHTML = products.toString();
      })
   });
</script>

Controller:

public function edit($id)
    {
        $where = array('id' => $id);
        $readAction  = Order::where($where)->first();
        $readAction->load('products');
        
        return Response::json($readAction);
    }

Route:

Route::resource('readAction', 'Customer\VehicleController');

This is putting [object Object],[object Object],[object Object] into the input in the modal which is great but how do i convert that to a string array?

Thank you in advance.

Feb
15
1 week ago
Activity icon

Replied to Another Pivot Table Issue

Hey @ignium

Thanks for your suggestion. Unfortunately my edit function is called after return view. I probably should have included the JS in my last post. Apologies.

So when the row edit button is clicked in the view, its taking the id of the row and calls the data via the JS to the edit function in the controller. The edit function then takes all the data where the ID matches and passes it back ti the view via JSON & populates the modal with the data. The bit i'm stuck on is how to pass the product data from Json into the view. I tried using an input field with an ID of products but nothing showed.

This makes sense as technically in the console i'm displaying an array. So the bit i'm stuck on is how to pass the json array into the modal. I know the products for that record are populating as i can see them in the console.

View:

            <div class="row">
                            <div class="col-sm-4">
                                <label>Make</label>
                                <input type="text" readonly class="form-control" name="make" id="make">
                            </div><!-- end col -->
                            <div class="col-sm-3">
                                <label>Model</label>
                                <input type="text" readonly class="form-control capi" name="mdl" id="mdl">
                            </div><!-- end col -->
                            <div class="col-sm-2">
                                <label>Engine</label>
                                <input type="text" readonly class="form-control" name="engine" id="engine">
                            </div><!-- end col -->
                            <div class="col-sm-3">
                                <label>Year</label>
                                <input type="text" readonly class="form-control" name="mdl_year" id="mdl_year">
                            </div><!-- end col -->
                        </div><!-- end row -->

            <div class="row">
                            <div class="col-sm-12">
                                <p>Products:</p>
                            </div><!-- end col -->
                            <div  class="col-sm-3">
                                <!-- <div id="products" ></div> -->
                            </div>
                        </div><!-- end row -->

<script>
  /* When click view open modal */
  $('body').on('click', '#edit', function () {
      var readAction_id = $(this).data('id');
      $.get('readAction/' + readAction_id +'/edit', function (data) {
          $('#edit-modal').modal('show');
          $('#readAction_id').val(data.id);
          $('#make').val(data.make);
          $('#mdl').val(data.mdl);
          $('#mdl_year').val(data.mdl_year);
          $('#engine').val(data.engine);
          $('#transmission').val(data.transmission);
          $('#products').val(data.products);
          console.log(data.products);
      })
   });
</script>

Route:

Route::resource('readAction', 'Customer\VehicleController');

Controller:

public function edit($id)
    {
        $where = array('id' => $id);
        $readAction  = Order::where($where)->first();
        $readAction->load('products');
        
        return Response::json($readAction);
    }

The good news is i can see the products loaded for the record in the console but the difficulty i'm having is displaying that in the view. All of the other inputs are populated based on the ID of the input matching the data form the JS.

Console data when i open a record:

(3) [{…}, {…}, {…}]
0: {id: 1, product_name: "Product One", product_cost: "0", product_sale: "0", status: "Displayed", …}
1: {id: 3, product_name: "Product Two", product_cost: "0", product_sale: "10", status: "Displayed", …}
2: {id: 7, product_name: "Product Three", product_cost: "0", product_sale: "0", status: "Displayed", …}
length: 3

Thanks dude.

Feb
14
1 week ago
Activity icon

Replied to Admin And User Login Pages

@randy_johnson you could separate your controllers by admin & user by putting all of the admin controllers in an admin folder & vice versa i.e

/App
    /Admin (folder)
        -AdminDashboardController
        -AdminProductController
        -EtcController
    /Customer (folder)
        -CuDashboardController
        -CuProductController
        -CuEtcController

This way it keeps the logic separate and will be cleaner and more scalable.

Hope that makes sense. Let me know if you need any clarification on the example file tree ;).

Activity icon

Replied to Laravel Nova-flexible-content

There are a couple of different ways of doing it but AJAX will probably be your best bet.

Activity icon

Replied to Laravel Nova-flexible-content

Dude, yeah it may be 2 models but you'd be working with Eloquent. So its only 2 queries for 2 different types of data.

//DashboardController
use App\Post; // This is your model

public function show() 
{
    $posts = \App\Post::where('status', 'displayed')->get();
    $gallery = \App\Gallery::where('status', 'displayed')->get();

    return view('your_page_name', compact('posts'));
}

and again 2 foreach loops for the data you wish to display.

You mentioned that you want to store all of your data in one column on a table? I would advise against this as it will cause you all sorts of nightmares when decoding & trying to display the data in the format that you want.

You would be better off separating your data so that its manageable & scalable.

Activity icon

Replied to Laravel Nova-flexible-content

Hey @janmoes

I'm not sure what experience you currently have with Laravel but this is quite easily achievable.

The link i suggested was to get you started, whilst it may be "simple", it would be the foundation of what you're looking to do.

You could filter what content you would like shown on that particular page in a query on a status basis. (i.e if the status = displayed).... see controller for more info...

In your controllers you could then add various queries as required to call data & pass it to the view. For instance if you had all of your posts in a table you could call this in the controller as such:-

//DashboardController

use App\Post; // This is your model

public function show() 
{
    $posts = Post::where('status', 'displayed')->get();

    return view('your_page_name', compact('posts'));
}

Then in your view you could do something like:-

<h5>These are our recent posts</h5>

<div class="row">
@foreach ($posts as post)
    <div class="col-md-12">
        <h5>{{$post->title}}</h5>
        <p>{{$post->content}}</p>
    </div>
    @endforeach
</div>

This would return all of the posts thats status = displayed.

Activity icon

Replied to View Testing Returns Undefined Variable: Errors

No worries, glad you got it sorted.

Activity icon

Replied to Laravel Nova-flexible-content

Hey @janmoes

Is your restricted page behind a login?

Depending on what you're looking to do Nova may be overkill. Is this for a business or a personal project? Nova is a paid solution where as something like Voyager is FOC i believe.

What you're describing though sounds like "CRUD" (Create, Read, Update, Delete). Have a look at this and let me know what you think: https://scotch.io/tutorials/simple-laravel-crud-with-resource-controllers

Activity icon

Replied to View Testing Returns Undefined Variable: Errors

Can you show us your controller & route?

If i'm understanding your initial post correctly, lets say your page name (located in the view folder) is servicing.blade.php.

Normally in your controller you would have:-

//ServicingController

public function show()
{
    return view('servicing');
// or if its in a folder within the view folder: return view('foldername.your_page_name');
}

Your route would then look something like:-

Route::get('servicing', '[email protected]');

What is it your trying to pass to your view page? Is it something from your database? As this would normally be assigned to a variable and passed into your view. Something like

//ServicingController
use App\Servicing; 

public function show()
{
    $oil = Servicing::all();

    return view('servicing', compact('oil'));
}

Then in your view you would have your fields:-

{{ $oil->name }} // example`
Activity icon

Replied to Admin And User Login Pages

Hey @randy_johnson

I think a lot of it comes down to personal preference & also what you're building along with how secure you need the system to be? If it was for an enterprise setup i would suggest separate login areas and separate user tables.

What are you looking to build? As this will determine most of the answers.

On my current project i'm using the same login form for both admin & users but where they are redirected to and what they have access to is dependant on what user level they are. depending on what you go for, the middleware & the auth files will handle most of the leg work & redirection once setup to how you want it.

Interms of the actual login system, i would suggest checking out "https://scotch.io/tutorials/simple-and-easy-laravel-login-authentication".

Out of the box most of the scaffolding is done by Laravel. from there you can adjust accordingly.

Once the login system has been built, i would suggest separate views & controllers for Admin / User retrospectively as it will be a lot cleaner, easier & scalable. As a general rule of thumb, i suggest using one controller per view page otherwise it all gets a bit messy & confusing when you come back to it later.

Activity icon

Replied to Another Pivot Table Issue

Thanks @ignium. So i took your advice & used route model binding, the good news is that the product data for the order is passed to the modal (confirmed in the browser console) however the bad news is, is i'm not sure about how to display the data. If i use a @foreach loop i get undefined variables which makes sense as the $readAction variable is declared after the ``return view``` statement however i'm not sure how to pass the Json product data as a foreach in the modal.

In the controller, the data is called via

public function edit($id)
    {
        $where = array('id' => $id);
        $readAction  = Order::where($where)->first();
        $readAction->load('products');
        
        return Response::json($readAction);
    }

Please can you advise the best course of action to output the data in the view.

Thank you in advance.

Feb
13
1 week ago
Activity icon

Replied to Another Pivot Table Issue

Hey @ignium

So i've made some progress, although the bit i'm stuck on is how to pass the ID of the record in the modal to the query in the controller.

So in controller i've got:

$orders = Order::find('12')->products()->orderBy('product_sale')->get();

However hardcoding the order id isn't ideal.

and in my view i have

            <div class="row">
                        @foreach($orders as $product) 
                                <div class="col-sm-4">
                                    <small> {{ $product->product_name }} £{{ $product->product_sale }}</small>
                                </div>
                            @endforeach
                        </div><!-- end row -->

So my question is, how do i pass the ID to the query inside of the modal so that it only returns the product data related to that order.

Activity icon

Replied to Another Pivot Table Issue

Hey @ignium

I see what you mean. You're absolutely right $filereqP is returning all orders with a status of pending. With this i pass the variable to the view then into the table and display the data in the table like this:-

<div class="tab-content">
                    <div id="pending" class="tab-pane active">
                        <table class="table table-dark table-no-more table-bordered table-striped mb-0 text-center table-sm">
                            <thead>
                                <tr>
                                    <th scope="col">Make</th>
                                    <th scope="col">Model</th>
                                    <th scope="col">Year</th>
                                    <th scope="col">Engine</th>
                                    <th scope="col">Gearbox</th>
                                    <th scope="col">Action</th>
                                </tr>
                            </thead>
                             <tbody>
                                @foreach($filereqP as $pending)
                                    <td data-title="Make">{{ $pending->make }}</td> 
                                    <td data-title="Model" class="capi">{{ $pending->mdl }}</td>
                                    <td data-title="Year">{{ $pending->mdl_year }}</td>
                                    <td data-title="Engine">{{ $pending->engine }}</td>
                                    <td data-title="Gearbox">{{ $pending->transmission }}</td>
                                    <td>
                                        <a href="javascript:void(0){{ $pending->id }}" id="edit" data-toggle="modal" data-target="#modal-two" data-id="{{ $pending->id }}" class="btn btn-sm btn-outline-light"><i class="fa fa-eye"></i></a>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div><!-- end displayed pane -->

Then then when i click the view button it fires up the modal.

Your 1st & second point make sense. Thats why the @foreach($filereqP as $order) is pulling 6 null values because that's the total no of records in the pivot table and therefore in my foreach its calling on all of the records for all of the orders and displaying null as i assume it cant determine which order to call them against.

What would you suggest the best way to call the product data for the specific order record inside of the modal? Should i create a separate variable in the controller and call then ID of the modal record opened?

If it helps this is the query in the controller

$filereqP = Order::where('user_id', $authUid)->where('stage', 'pending')->with('products')->get();

Thank you again for this.

Activity icon

Replied to Another Pivot Table Issue

Hey @ignium. You definitely have.

So essentially the view page shows a table of which is populated by all of the records with a status of pending. When i click to view the record, the data is populated into a modal via the JS script in my previous post.

I think the bit i'm struggling to get my head round is that inside the modal, i only need to loop through the products for that order but if i use

@foreach($filereqP->products as $product)

i get

Property [products] does not exist on this collection instance.

or if i use

                @foreach($filereqP->order->products as $product)
                                    <div class="col-sm-4">
                                        <small>{{ $product->product_name }} £{{ $product->sale }}</small>
                                    </div>
                                @endforeach

then i get

Property [order] does not exist on this collection instance.

however if i use

@foreach($filereqP as $order) 
                            @foreach($order->products as $product)
                                    <div class="col-sm-4">
                                        <small>{{ $product->name }} £{{ $product->sale }}</small>
                                    </div>
                                @endforeach
                            @endforeach

then it returns 6 x £ when i know that there should only be 3 product values from the pivot table associated with this record.

Sorry for the 1001 questions dude.

Activity icon

Replied to Another Pivot Table Issue

Hey @ignium. You are a total legend. Thank you. If i could buy you a beer, i would buy you many lol.

Thank you for the resource also. That makes a lot of sense. I guess i was just overcomplicating it.

I still think there's some witchcraft in there as i don't get how it knows which column to put the order_id & the product_id in but it works.

In regards to calling the data, currently, i have a table which when the user clicks to view the record, it takes the id of the row, opens the modal and the data is called via a resource route to the controller to fetch the data and return the values into the input fields based on their id.

<script>
  /* When click edit user */
  $('body').on('click', '#edit', function () {
      var readAction_id = $(this).data('id');
      $.get('readAction/' + readAction_id +'/edit', function (data) {
         $('#modal-two').html("");
          $('#show-modal').modal('show');
          $('#readAction_id').val(data.id);
          $('#make').val(data.make);
          $('#mdl').val(data.mdl);
          $('#mdl_year').val(data.mdl_year);
          $('#engine').val(data.engine);
          $('#transmission').val(data.transmission);
        //   console.log(data.id);
      })
   });
</script>

My question is, to call this data, in my controller i put

        $filereqP = Order::where('user_id', $authUid)->where('stage', 'pending')->with('products')->get();

and passed this to my view. Then in my view i have

            <div class="row">
                            @foreach($filereqP as $order)
                                <div class="col-sm-4">
                                    <small>{{ $order->product_name}} £{{ $order->product_sale}} </small>
                                </div>
                            @endforeach
                        </div><!-- end row -->

however only the £ is outputted twice to the modal for the products but no product name. Now is this because its not being picked up by the JS and displaying the data inside the modal or is it that my syntax is incorrect?

I really appreciate your help dude.

Activity icon

Awarded Best Reply on Getting Data Between Date Ranges

Hey @jesse_orange_newable

Carbon is great for this. You could use something like:

$date = \Carbon\Carbon::today()->subDays(30);

        $userRegisteredCount = \App\User::where('created_at', '>=', $date)
                    ->where('status', 'approved')
                    ->count();

$userRegistered = \App\User::where('created_at', '>=', $date)
                    ->where('status', 'approved')
                    ->get();

Then in your view you would use {{ $userRegisteredCount }}

Or if you wanted to list them you could change it to ->get()

@foreach ($userRegistered as $registered)

{{ $userRegistered->name }}

@endforeach

You can then just pass the variable inside compact in your view like so:-

return view(
            'your_view_name', 
            compact
            (
                'userRegisteredCount'
        'userRegistered'
            )
        );

Activity icon

Awarded Best Reply on Load Additional Data Through DashboardController

Fair play. A repository would probably be the way to go.

Feb
12
1 week ago
Activity icon

Replied to Another Pivot Table Issue

Hey @ignium

Thanks for your feedback.

In regards to obtaining the ID, could i use a last inserted id function? I'm struggling to get my head round this pivot table thing and how to insert the correct data into the pivot table.

In your 2nd point, i could assign a variable to the request such as $product = 'product_id' => $request->input('option_id'), but i feel as though this would do more harm than good as it would be taking it as a string?

Activity icon

Replied to Another Pivot Table Issue

@ignium thanks for your response.

you're absolutely right. I think i stared at it too long to see lol.

However even when i change to: $order->products()->attach('product_id') i get: Call to a member function products() on null

Activity icon

Started a new Conversation Another Pivot Table Issue

Hi All

This seems to be the topic of the week lol.

I'm still trying to figure out this pivot table scenario with orders and products and i think i've got it sussed. Except the fact that i cant insert data into the tables due to Call to a member function orders() on null.

I have a pivot table called order_product of which has the columns order_id & product_id.

In my models i have:

Order model: belongsToMany products

public function products()
    {
        return $this->belongsToMany(Product::class);
    }

Product model belongsToMany orders

public function orders()
    {
        return $this->belongsToMany(Order::class);
    }

In the controller, when i $request-> the data and create a record in the orders table it works. However when i added the attach method i getCall to a member function orders() on null Please can someone tell me where i'm going wrong"-

Controller

$form_data = array(

'product_id' => $request->input('option_id'), // this is to accept the product_id checkboxes in an array.
'make'            => $request->make,
'mdl'             => $request->mdl,
'mdl_year'        => $request->mdl_year,
'engine'          => $request->engine,
'transmission'    => $request->transmission,
  );

        Order::create($form_data);

        $order = \App\Order::find('id');
        $order->orders()->attach('product_id');
        
        return redirect.......

Please can someone tell me where i'm going wrong as i've tried many different ways and i've been stuck on this for nearly a week.

Thank you in advance.

Activity icon

Replied to POST 500 Internal Server Error AJAX POST Request

What did your error logs say?

May be worth changing Route::post to Route::resource.

Activity icon

Replied to Getting Data Between Date Ranges

Hey @jesse_orange_newable

Carbon is great for this. You could use something like:

$date = \Carbon\Carbon::today()->subDays(30);

        $userRegisteredCount = \App\User::where('created_at', '>=', $date)
                    ->where('status', 'approved')
                    ->count();

$userRegistered = \App\User::where('created_at', '>=', $date)
                    ->where('status', 'approved')
                    ->get();

Then in your view you would use {{ $userRegisteredCount }}

Or if you wanted to list them you could change it to ->get()

@foreach ($userRegistered as $registered)

{{ $userRegistered->name }}

@endforeach

You can then just pass the variable inside compact in your view like so:-

return view(
            'your_view_name', 
            compact
            (
                'userRegisteredCount'
        'userRegistered'
            )
        );

Activity icon

Awarded Best Reply on POST 500 Internal Server Error AJAX POST Request

What are you getting in your error logs?

Also this: url:"{{ route('search') }}", is different to Route::post('/data/action',.....

Correct me if i'm wrong but wouldn't it be:

$.ajax({  
url: "{{ url('/data/action) }}",
method:"POST",

Route::post('/data/action', '[email protected]')

Activity icon

Replied to POST 500 Internal Server Error AJAX POST Request

What are you getting in your error logs?

Also this: url:"{{ route('search') }}", is different to Route::post('/data/action',.....

Correct me if i'm wrong but wouldn't it be:

$.ajax({  
url: "{{ url('/data/action) }}",
method:"POST",

Route::post('/data/action', '[email protected]')

Activity icon

Replied to Load Additional Data Through DashboardController

Fair play. A repository would probably be the way to go.

Activity icon

Replied to Load Additional Data Through DashboardController

Hey @dutchroyals

I had a similar scenario, i had queries that i only needed on the dashboard so simply i inserted into the view. For instance...

Controller:

public function index()
    {  
        
        $date = \Carbon\Carbon::today()->subDays(7);
        $recentDealerAppCount = \App\User::where('created_at', '>=', $date)
                    ->where('status', 'approved')
                    ->count();

        // List all all recently approved dealers
        $recentDealer = \App\User::where('created_at', '>=', $date)
        ->where('status', 'approved')
        ->limit('5')
        ->get();

// All other queries.....

return view(
            'yourviewnamehere', compact
            (
                'recentDealer',
                'recentDealerAppCount',
                'changelog',
                'review'
            )
        );

And then in view you could do something like:-

@if ($recentDealer->count())
     @foreach ($recentDealer as $recentDealer)

    <!-- your div / li etc here -->

      @endforeach
@else
No data found
@endif
Activity icon

Started a new Conversation Stuck Inserting Into Pivot Table.

Hi All

I'm still trying to figure out this pivot table scenario with orders and products and i think i've got it sussed. Except the fact that i cant insert data into the tables due to an undefined variable.

User model: HasManyOrders

public function orders()
    {
        return $this->hasMany(Order::Class);
    }

Order model: hasManyProducts

public function products()
    {
        return $this->HasMany(Product::class);
    }

Product model belongsToMany orders

public function orders()
    {
        return $this->belongsToMany(Order::class);
    }

In the controller, when i $request-> the data and create a record in the orders table it works. However when i added the attach method i get Call to a member function orders() on string. Please can someone tell me where i'm going wrong"-

Controller

$form_data = array(

'product_id' => $request->input('option_id'),
'make'            => $request->make,
'mdl'             => $request->mdl,
'mdl_year'        => $request->mdl_year,
'engine'          => $request->engine,
'transmission'    => $request->transmission,
  );

        Order::create($form_data);

        $order = Order::find(['id']);
        $form_data->orders()->attach($order);
        
        return redirect.......

Thanks in advance.

Feb
10
1 week ago
Activity icon

Replied to Column Sorting In Laravel Paginate On Table

You could sort by date in your query with ->orderBy('created_at', 'desc')

But change created_at to suit your table.

Activity icon

Replied to Passing Two Values From The Dropdown To The Controller

I was trying to do the same the other day and it was recommended that I use a pivot table to do this. I would suggest you look into it also.

Feb
09
2 weeks ago
Activity icon

Replied to Display Data From One Table But With Products From Another

Hey @sinnbeck just coming back to this after doing some reading, please can you confirm if i'm on the right path? or if i'm missing anything... I've set my many to many relationships up in the orders model & products model..

// orders table
public function products()
    {
        return $this->belongsToMany('App\Product');
        $order->product()->attach($product_id); // Is this correct?
    }

// products table   
public function orders()
    {
        return $this->belongsToMany('App\Order');
    }

If i understand correctly, when i place an order with products Laravel will handle the input into the pivot table (order_product) using the $order->product()->attach($product_id);

Is this correct?

Thanks in advance.

Activity icon

Replied to Cant Register Using Mysite.test, Just Localhost:8000

Can you post your view form, route & controller.

Activity icon

Replied to Display Data From One Table But With Products From Another

@sinnbeck Thanks for the link, unfortunately i'm not subscribed atm so only get the free videos. will do some more googling. Thanks for your help.

Activity icon

Replied to Display Data From One Table But With Products From Another

I think that the Pivot Table could help alot as i also need to generate an invoice based on the options selected in the fields aswell at some point soon.

Activity icon

Replied to Display Data From One Table But With Products From Another

Cool. thanks.

So how would i insert to the OrderTable & the PivotTable when the form is submitted?

Would it be as simple as something like:-

$form_data = array(

            'make'            => $request->make,
            'mdl'             => $request->mdl,
            'mdl_year'        => $request->mdl_year,
            'engine'          => $request->engine,
            'transmission'    => $request->transmission,
            'reg_no'          => $request->reg_no,
            'fuel_type'       => $request->fuel_type,
            'ecu_type'        => $request->ecu_type,
            'req_by'          => $request->req_by,
            'product_id' => $request->input('option_id'),
            'user_id'         => $request->user_id,
        );

AutomotiveOrder::create($form_data);
PivotTable::create($form_data);

And likewise on the other side, how do i call the data? would i call it from the Pivot Table or the order table?

Currently i have the users table which i've said has many orders and the orders table belongs to the users table.

Activity icon

Replied to Display Data From One Table But With Products From Another

Of course. I did look at Pivot tables but got too confused lol.

Activity icon

Replied to Display Data From One Table But With Products From Another

Hey @sinnbeck

It holds multiple ID's per row.

Activity icon

Started a new Conversation Display Data From One Table But With Products From Another

Hi All

The user submits a form into the Order Table which has options generated from the Product Table in a foreach loop.

The user selects the options via checkboxes of which insert the selected product ID array into the Order Table.

So the question is, on the admin side, how to i display the product ID array but call all of the data from the products table.

i.e in the order table how do i take the product_id column with the values "1","3","5" & use those to display

{{ $product->prod_name }}{{ $product->prod_value }}

Thanks in advance.

Activity icon

Replied to Laravel Muliple Submit In One Form

@phoenix5 there must be more to the form than 3 buttons?

Where are all of the input fields? (such as the @csrf field that was generated in the dd()?

Where are your opening & closing form tags?

Activity icon

Replied to Calculate Value Based On Selected Options

Hi All

Thanks for your inputs. Apologies, i think i may not have explained myself correctly.

The options column has to remain as a string value so that the selected options output to admin as a description of the option when the inputted form is displayed in the admin portal.

The form is for vehicle servicing, so what i'm trying to do is kind of like this:-

<label>Service Options</label>
<select required type="text" name="service_options" class="form-control" >
    <option value="" hidden>Select Option</option>
    <option>Minor Service</option>
    <option>Major Service</option>
    <option>Vehicle Health Check</option>
 </select>

// These are called via a foreach from another table in the db)
<label>Optional Extras</label>
<select required type="text" name="opt_extras" class="form-control" >
    <option value="" hidden>Select Option</option>
    <option>Opt Extra One</option>
    <option>Opt Extra Two</option>
    <option>Opt Extra Three</option>
 </select>

Then depending on which options are selected from each table calulate the total and input to a separate amount column the total value. i.e if user selects Minor Service & Opt Extra One then its £150 else if ....

Feb
08
2 weeks ago
Activity icon

Replied to Calculate Value Based On Selected Options

Hey @bobbybouwmann thanks for your suggestion however i want the text input of the option to appear in the db. I'm trying to basically work out a value that says if option 3 is selected and another option is selected then calculate and input into amount column.

Activity icon

Replied to Cant Register Using Mysite.test, Just Localhost:8000

Hi @tjyoung

What happens when you try to register using mysite.test?

do you get a 404?

Have you checked the error logs?

Activity icon

Started a new Conversation Calculate Value Based On Selected Options

Afternoon All

I'm trying to work out the best way to calculate particular fields based on the option selected.

Currently i have a dropdown like this...

<select required type="text" name="options" class="form-control" >
     <option hidden>Select Option</option>
     <option>Example Option One</option>
     <option>Example Option Two</option>
     <option>Example Option Three</option>
 </select>

Now i can't add a value to the option field as this would insert the incorrect data into the options column as this is pulled from the name attribute so wondering should i do a separate if statement in the controller that works out the value and then posts to a hidden field?

Thanks in advance all.

Feb
06
2 weeks ago
Activity icon

Replied to Many To Many Tables

@ahmeddabak - Essentially they are the input form fields that the user selects regarding their vehicle. This form also draws optional chargeable service options from the products table that i was planning to put a foreach loop for on the form.

Activity icon

Replied to Many To Many Tables

Hey @ahmeddabak just coming back to this, just prepping my migrations & models. After reading Laravels docs, i'm a little unclear on the one to many / many to many. Essentially, i have a form that the dealer fills in. The form has input fields and a selection of options with each option costing a different amount. Essentially, i've drafted the models up as follows:-

// App\User

protected $fillable = [ 'usual fields.....' ];

 public function invoice()
    {
        return $this->hasMany(App\Invoice);
    }
___________________________

// App\Invoice


protected $fillable = [
        'user_id', 'order_id', 'paid_at', 'payment_method', 'amount'
    ];

public function order()
    {
        return $this->hasMany(App\Order);
    }

___________________________

// App\Order

protected $fillable = [
        'user_id', 'make', 'mdl', 'mdl_year', 'engine', 'transmission', 'fuel_type', 'reg_no', 'stage', 'product_id'
    ];

    public function invoice()
    {
        return $this->belongsTo('App\Invoice');
    }

___________________________

// App\Products

protected $fillable = [
        'product_name', 'product_cost', 'product_sale', 'status'
    ];

My plan is to do a product foreach loop on the order page for users to select multiple products at different values.

The bit where i'm confused is the inverse relationship, on the App\Order should i not have $this->hasMany('App\Product);?

Also when i insert into the Order page how does it insert into the invoice table etc etc.

Huge thank you in advance. Just struggling to get my head round this lol.