mattnewark

Experience

5,230

0 Best Reply Awards

  • Member Since 1 Year Ago
  • 14 Lessons Completed
  • 0 Favorites

6th August, 2018

mattnewark left a reply on Getting Data Into Vue Component • 1 month ago

morning @wood4283,

I have now changed the code to the below, which works, but the issue I had was that when I clicked on the first button the data would be displayed correctly but when I clicked any other buttons the data from the original button click would be displayed. I have noticed in the vue tools that the child component disappears when I click on any other buttons so I had to add the if at the top, do you know of any other way of doing this in vue?.

vm = null;
            function openNav(InvoiceId) {
                if(vm){
                    vm.UpdateInvoice(InvoiceId);
                    return;
                }
                vm = new Vue ({
                el: '#mySidenav',
                data: function(){
                    return {
                        invoice : {}   
                    }                
                },
                methods: {
                    UpdateInvoice: function(InvoiceId){
                        axios.post('accounts/show-notification/'+InvoiceId)
                        .then(response => {
                            this.invoice = response.data
                        })                       
                        .catch(function (error) {
                            console.log(error)
                        });
                    }
                },
                mounted() {
                        this.UpdateInvoice(InvoiceId);
                    },
                })
                document.getElementById("mySidenav").style.transform = "translateX(-450px)";
            }

3rd August, 2018

mattnewark left a reply on Updating A Vue Instance With New Data • 1 month ago

@tykus,

Maybe that is what the issue is..

When I click on the button it then loads a component that loads a template:

<template> 
<div>   
    <div class="row">
    <div class="col-5">
        <h6 class="white">ACTION CENTER</h6>
    </div>
    <div class="col-6">
        <a href="javascript:void(0)" id="closeNav" class="closebtn" onclick="closeNav()">close</a>
    </div>
  </div>  
  <div class="card">
    <div class="card-body">
      <div class="row">
          <div class="invoiceHeader col-12">Invoice Details</div>
          <div class="invoiceDetails">
            Invoice # {{ invoice.InvoiceNo }}<br>
            Price: £{{ invoice.Price }}<br>
            VAT: £{{ invoice.Vat }}<br>
            Total: £{{ invoice.Total }}<br>
            Date: {{ invoice.InvoiceDate | FormatDateCreated }}<br>
          </div>
      </div>
      <br>
      <div class="row">
          <span v-for="(payment,index) in invoice.Payments">
          <div class="invoiceHeader col-12">Payments Taken</div>
            <div class="invoiceDetails">
              Payment Type: {{ payment.PaymentType }}<br>
              Total : £{{ payment.Total }}<br>
              Payment Date: {{ payment.PaymentDate | FormatDateCreated }}<br>
            </div>
          </span>
      </div>
      <br>
      <div class="row">
          <span v-for="(CreditNote,index) in invoice.CreditNotes">
              <div class="invoiceHeader col-12">Credit Note Details</div>
              <div class="invoiceDetails">
                Credit Note # {{ CreditNote.CreditNoteNo }}<br>
                Date: {{ CreditNote.CreditNoteDate | FormatDateCreated }}<br> 
                Total: £{{ CreditNote.Total }}<br>
              </div>
          </span>
      </div>
      <br>
      <div class="grid-container grid-container--fill">

        <form :action="'accounts/get-invoice/' + invoice.InvoiceNo" target="_blank" >
            <button class="invoiceDownload" Type="submit">
                <div>
                    <div class="buttonIcon">
                        <i class="material-icons buttonIconSize">description</i>
                    </div>
                    <div class="buttonLabelBottomLeft">Invoice</div>
                </div>
            </button>
        </form>

         <form :action="'accounts/get-schedule/' + invoice.ScheduleId" target="_blank">
            <button class="invoiceDownload"  Type="submit">
                <div class="buttonIcon">
                    <i class="material-icons buttonIconSize">format_list_numbered</i>
                </div>
                <div class="buttonLabelBottomLeft">Schedule</div>
            </button>
        </form>

      </div>
     
    </div> 
    </div>
</div>

</template> 

<script>
    export default { 
        props: ['invoice'],
        filters: {
            FormatDateCreated: function(date) {
                return moment(date).format('L - LTS')
            }
        },    
        mounted() {
            
        }
    }
</script>

I am new to vue so what would I have to do to add the child component everytime I click a button?

mattnewark left a reply on Updating A Vue Instance With New Data • 1 month ago

Hi @tykus,

Thanks for replying, That is correct. You click on a view more button and get the invoice details in the side nav and then you can click another view more button but it does not update the side nav. It keeps the data from the first clicked button. When I checked the vue tools it seems to remove the child component after the initial click..

mattnewark started a new conversation Updating A Vue Instance With New Data • 1 month ago

Good morning,

I can click on a button the data will show correctly from an API, when I click on another button and get different data it does not update the data. I have found when using the vue tools in chrome that when I click another button it removes the child component and only leaves the root. Can I get around this issue using the vue instance? Below is what I have at the moment and it is working but I was wondering if there is a better way:

vm = null;
            function openNav(InvoiceId) {
                if(vm){
                    vm.UpdateInvoice(InvoiceId);
                    return;
                }
                vm = new Vue ({
                el: '#mySidenav',
                data: function(){
                    return {
                        invoice : {}   
                    }                
                },
                methods: {
                    UpdateInvoice: function(InvoiceId){
                        axios.post('accounts/show-notification/'+InvoiceId)
                        .then(response => {
                            this.invoice = response.data
                        })                       
                        .catch(function (error) {
                            console.log(error)
                        });
                    }
                },
                mounted() {
                        this.UpdateInvoice(InvoiceId);
                    },
                })
                document.getElementById("mySidenav").style.transform = "translateX(-450px)";
            }

As you can see from the above I am using an 'if' to check to see if the instance is there and, if it is, just update otherwise create a new one. I just wanted to see if there was a better way or is this it?

Thanks

2nd August, 2018

mattnewark left a reply on Getting Data Into Vue Component • 1 month ago

Hi @jimmck,

Thanks for getting back to me, which blade file are you talking about. All the files are above.

Thanks @ejdelmonico , I will give that a go.

1st August, 2018

mattnewark left a reply on Getting Data Into Vue Component • 1 month ago

Hi @ejdelmonico Thanks for getting back to me.

So, I have changed the layout and have problem=response

success:function(response){
                            console.log(response);
                            problem=response;
                        },

and have added the vue instance in the app.js file but the problem object is still empty with no errors?

Thanks

31st July, 2018

mattnewark left a reply on Getting Data Into Vue Component • 1 month ago

Ok, So I have added var support = {}; to the top of my layout blade as this has stopped the above error but I am not getting any data into the root of the component, it is still empty.

mattnewark started a new conversation Getting Data Into Vue Component • 1 month ago

Hi All,

I am trying to get the data into either root component or a child component but having troubles could someone please have a look at the below and help me out: app.js

Vue.component("my-side-nav",
        require('./components/MySideNav.vue'),
);

document.addEventListener('DOMContentLoaded', (function() {
const MySideNav = new Vue({ 
    el: '#mySidenav',
    data: {
        problem : {}
    },
    computed: {
        DateCreatedFormatted: function() {
            return moment(this.problem.DateCreated).format('Do MMMM YYYY') 
        }
    },
    filters: {
        FormatDateCreated: function(date) {
            return moment(date).format('L - LTS')
        }
    }    
})
}), false);

My Layout that will call the slide in sidebar that has the data in:

function openNav(problemId) {
                    $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        }
                    });
                    $.ajax({
                        url:"support/show-notification/"+problemId, 
                        dataType:'json',
                        type:"POST",
                        data:{},
                        success:function(response){
                            console.log(response);
                            support.problem=response;

                        },
                        error: function(textStatus, errorThrown) {
                             console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
                        }
                    });   
                    document.getElementById("mySidenav").style.transform = "translateX(-450px)";
            }

The vue template:

<template>
<div>   
    <div class="row">
        <div class="col-5">
            <h6 class="white">ACTION CENTER</h6>
        </div>
        <div class="col-6">
            <a href="javascript:void(0)" id="closeNav" class="closebtn" onclick="closeNav()">close</a>
        </div>
      </div>  
    <!-- If there are other notifications -->
    <div class="card">
      <div class="card-body">
    <p><b>Ticket: {{problem.ProblemId}}</b></p>
</div>
    </div>
</div>
</template>

<script>

    export default { 
        name: 'my-side-nav',
        mounted() {
            console.log('Component mounted.')
        }
    }
</script>

I have had this working when I place the new vue inside the layout file but I would like to have this in the app.js so I can access it globally.

When I click on the button to open the side bar I get the below error:

Uncaught ReferenceError: support is not defined
    at Object.success (support:377)
    at i (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at y (jquery.min.js:4)
    at XMLHttpRequest.c (jquery.min.js:4)

and in the vue console in chrome I have no data in the root or the my-side-nav.

I am new to vue so would be good to get this working.

Thanks

15th June, 2018

mattnewark left a reply on 301 Redirects • 3 months ago

@36864 / @tykus

I will hang my head in shame, I think it was a caching issue...

Thank you guys for all your help.

mattnewark left a reply on 301 Redirects • 3 months ago

@36864

By the looks of things it does the same thing:

// Route::get('/services/battery-recycling/', function(){ 
//     return Redirect::to('/waste/batteries-disposal', 301); 
// });
Route::get('services/battery-recycling', function(){ 
    return Redirect::to('waste/batteries-disposal', 301); 
});

still has the third step.

Thanks

mattnewark left a reply on 301 Redirects • 3 months ago

Hi @tykus,

Thanks for the reply, That is how the old site worked previously and I am using the standard Laravel htccess file. Also, I'm using 5.4 and not 5.5.

So I'm not sure why it is adding the extra hop instead of just going straight to the destination.

mattnewark started a new conversation 301 Redirects • 3 months ago

Afternoon all,

I am having a issue with redirecting an old url to a new one after site change, at present I have the below code:

Route::get('/services/battery-recycling/', function(){ 
    return Redirect::to('/waste/batteries-disposal', 301); 
});

It is directing correctly but it is adding a hop in the redirect and I can't seem to stop it, this is what is happening:

/services/battery-recycling/

redirects to

/services/battery-recycling

and then finally gets to it's destination

/waste/batteries-disposal

How can I remove the middle step? so remove the step that gets rid of the trailing slash.

Thanks

14th February, 2018

mattnewark left a reply on Storing API Access_tokens • 7 months ago

So after a little research I have decided that I am going to add the content of the API return in a session and then destroy it on logout.

$content = json_decode((string) $res->getBody(), true);
session()->put($content);

13th February, 2018

mattnewark left a reply on Storing API Access_tokens • 7 months ago

@tykus would it just as well to create a new table with the email and the token and then when they logout delete the entry? @CJJ yes, passport authenticates the user when I send the username, password etc through guzzle. I then get a response with the token in it. I would like to have that token available to all controllers for the application. When they logout then this is cleared.

Thanks

mattnewark left a reply on Storing API Access_tokens • 7 months ago

Hi @CJJ

I have built an API using Passport and I would like to access it from another domain using Laravel and Guzzle. I would like to get the access_token and save it so that I can access it from every controller.

Thanks

mattnewark left a reply on Storing API Access_tokens • 7 months ago

Hi @tykus

So if I get the token from guzzle how would I add it to the env? once the user logs out I would like it to cleared?

Thanks

mattnewark started a new conversation Storing API Access_tokens • 7 months ago

Hi All,

I am thinking of using Laravel as a API client and using Guzzle, what I would like to know is what would be the best and most secure way of getting the auth token and saving it for all calls to the API? I have a call to the an API and I am getting the access token but I would like to have some idea how to store that for all calls etc.

Thanks

9th February, 2018

mattnewark left a reply on Count In A Transformer With Large Amount Of Information • 7 months ago

@lostdreamer_nl

Works a treat, thanks

mattnewark started a new conversation Count In A Transformer With Large Amount Of Information • 7 months ago

Hi guys,

I am trying to pass some data through an API using a transformer and I get time outs because of the amount of data, my controller is:

public function index()
    {
        $sites = Site::all();
        return Fractal::collection($sites, new SiteTransformer);
    }

Transformer

public function transform(Site $site) 
    {
        return [

            
            'SiteId' => $site->id,
            'SiteName' => $site->sitename,
            'SiteReference' => $site->sreference,
            'Address' => [
                'AddressLine1' => $site->saddress1,
                'AddressLine2' => $site->saddress2,
                'AddressLine3' => $site->stown,
                'AddressLine4' => $site->scounty,
                'Postcode' => $site->spostcode,
            ],
            'LiveAuditItemAmount' => $site->siteaudititems->count(),
            
        ];
    }

model

public function siteaudititems() {
        return $this->hasMany(SiteAuditItem::class, 'site_id', 'id');
    }

what would be the best way of getting the data through the API without a time out?

Thanks

22nd December, 2017

mattnewark left a reply on Symlinks • 9 months ago

Hi All,

I have got around the issue but just using the ```ln -s`` in the terminal.

Thanks

mattnewark left a reply on Symlinks • 9 months ago

Hello @wilburpowery

Thanks for the reply, the error that I get is:

 [ErrorException]
  symlink(): No such file or directory

Thanks

21st December, 2017

mattnewark started a new conversation Symlinks • 9 months ago

Hi All,

I need a little help in creating a symlink between the storage/app/public folder and the public folder. I have followed @Snapey tutorial on moving all folders apart from the public folder outside of the public folder and when I try and run the artisan command I get an error.

Could someone please point me in the right direction

Thanks

mattnewark left a reply on Uploading Image To The Storage Folder • 9 months ago

Hi,

I have fixed the issue, It was a queue process issue that was causing it to not save in the correct place.

mattnewark left a reply on Uploading Image To The Storage Folder • 9 months ago

Hi @Snapey

Could you please help me, I followed your help guide on moving the app folders out of the public_html folder and now I am having troubles getting it save images to the storage folder or the public folder that is inside the public_folder..

Thanks

20th December, 2017

mattnewark left a reply on Uploading Image To The Storage Folder • 9 months ago

Hi @RamjithAp,

I am now able to create the directories in the public folder by using the below:

if(!File::exists($_SERVER['DOCUMENT_ROOT']."/images/".$userName))
        {
            File::makeDirectory($_SERVER['DOCUMENT_ROOT']."/images/".$userName,0777,true);
        } 
        if(!File::exists($_SERVER['DOCUMENT_ROOT']."/images/".$userName."/".$auditTitle));
        {
            File::makeDirectory($_SERVER['DOCUMENT_ROOT']."/images/".$userName."/".$auditTitle,0777,true);
        }    
        if(!File::exists($_SERVER['DOCUMENT_ROOT']."/images/".$userName."/".$auditTitle."/".$date))
        {
            File::makeDirectory($_SERVER['DOCUMENT_ROOT']."/images/".$userName."/".$auditTitle."/".$date,0777,true);
        }

but when I try and save the image it is using the below url:

/home/custzone/auditcore/public//home/custzone/public_html/auditstaging/public/images/Title_Dan/2017-12-20/image_pUignBpKso.png

using this code:

$image = Image::make($this->auditimage['Base64Image'])
                    ->resize(1000, 1000, function ($constraint) {
                    $constraint->aspectRatio();})
                    ->save($fullPath.'/'.$this->filename);
                    $image->destroy();

I am assuming that the first part /home/custzone/auditcore/public/ is what is created using the save method, is there another method that I am able to use that does automatically add a directory structure?

Thanks

mattnewark left a reply on Uploading Image To The Storage Folder • 9 months ago

Hi @RamjithAp,

Thank you for the help, I was originally using File:: but the error I get is:

"message": "mkdir(): No such file or directory",
    "exception": "ErrorException",
    "file": "/home/custzone/auditstagingcore/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php",

Do you have any idea why this does not work?

Thanks

mattnewark left a reply on Uploading Image To The Storage Folder • 9 months ago

Hi @RamjithAp

Thank you for answer.

So my structure for the site is:

Root auditstagingcore app public_html auditstaging public images

What I would like to do is create the folder structure in the auditstaging->public->images folder and also save the images to it. for the life of me I am unable to find a way to to do this as everything relates to the auditstagingcore.

What would I need to do to the below to create the folders in the auditstaging->public->images folder:

if(!Storage::exists("/public/images/$userName"))
        {
            Storage::makeDirectory("/public/images/$userName");
        } 
        if(!Storage::exists("/public/images/$userName/$auditTitle"))
        {
            Storage::makeDirectory("/public/images/$userName/$auditTitle");
        }    
        if(!Storage::exists("/public/images/$userName/$auditTitle/$date"))
        {
            Storage::makeDirectory("/public/images/$userName/$auditTitle/$date");
        }
        $fullPath = "/public/images/$userName/$auditTitle/$date";
        return $fullPath;

and in turn what would I need to do to save the image to the above created folder in the below code:

$image = Image::make($this->auditimage['Base64Image'])->resize(1000, 1000, function ($constraint) {
                    $constraint->aspectRatio();})->save(storage_path().$this->fullPath.'/'.$this->filename, 50);
                    $image->destroy(); 

Thanks

mattnewark started a new conversation Uploading Image To The Storage Folder • 9 months ago

Hi Guys,

I am trying to upload images to the storage folder that is located above the public_html folder on my server so that I am able to hide my .env file etc.

So what I am doing is creating the directory in the storage folder which is working fine:

if(!Storage::exists("/public/images/$userName"))
        {
            Storage::makeDirectory("/public/images/$userName");
        } 
        if(!Storage::exists("/public/images/$userName/$auditTitle"))
        {
            Storage::makeDirectory("/public/images/$userName/$auditTitle");
        }    
        if(!Storage::exists("/public/images/$userName/$auditTitle/$date"))
        {
            Storage::makeDirectory("/public/images/$userName/$auditTitle/$date");
        }
        $fullPath = "/public/images/$userName/$auditTitle/$date";
return $fullPath;

Once this is done it is passed to the queue where it is processed and added to the file structure and uploaded to the DB:

public function handle()
    {
            if ($this->auditimage['Base64Image'])
            {
                Log::info('Adding New image ');
                $mime = explode(';', $this->auditimage['Base64Image']); 
                $mime1 = explode(':', $mime[0]);
                $type = explode('/', $mime1[1]); 

                $image = Image::make($this->auditimage['Base64Image'])->resize(1000, 1000, function ($constraint) {
                    $constraint->aspectRatio();});
                    Storage::putFileAs($fullPath, $image, $filename);
                    $image->destroy(); 

I have passed the fullpath and the filename from the controllers.

When I check the file structure it has created the directories with no issues but does not add the image to it and then in DB in the failed jobs table I get:

ErrorException: file_put_contents(/home/custzone/auditstagingcore/storage/app/public/images/Matthew_Morris/Title_Dan/2017-12-20): failed to open stream: Is a directory in /home/custzone/auditstagingcore/vendor/league/flysystem/src/Adapter/Local.php:198

Any help would be appreciated to get this to work.

13th December, 2017

mattnewark left a reply on Passport 'Unauthenticated' • 9 months ago

Morning @izhe

If you would like to do a test to confirm that the headers are set correctly add the below in your routes/api file:

Route::get('/testme', function (Request $request) { dd($request->header()); });

Use postman or which ever client you are using and go to url with your authenticated headers set and give me the response that you get

Also, are you trying to use HTTPS? if so you would need to add the completed code below to your .htaccess file:

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=

Maybe just try the above first and then do the test.

Thanks

8th December, 2017

mattnewark left a reply on Laravel Passport And SSL • 9 months ago

So, at the end of a lot of research I have found the answer. If you enter the below in the htaccess file it should for you if the Apache server is striping the auth headers:

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=

Well it has worked for me.

7th December, 2017

mattnewark left a reply on Laravel Passport "Unauthenticated" Error • 9 months ago

If you add this to your htaccess file it should work a treat:

Handle Authorization Header

RewriteCond %{HTTP:Authorization} ^(.) RewriteRule . - [e=HTTP_AUTHORIZATION:%1]

Thanks

mattnewark left a reply on Laravel Authorization Header Is Missing • 9 months ago

Hi @wljin,

Did you solve this issue?

mattnewark left a reply on Deploying Laravel • 9 months ago

@jdunsmore,

I have had it working previously with pointing the domain to the public folder so I am just going to revert everything back to what it was..

Thanks

mattnewark left a reply on Deploying Laravel • 9 months ago

@jdunsmore

I have started to upload everything again,

Thanks for your help

mattnewark left a reply on Deploying Laravel • 9 months ago

Hi

So I have all files apart from the public folder above the public_html in a folder called auditstagingcore, I have emptied the public folder contents into a folder called auditstaging below the public_html. I have also changed the index file to point to the new core folder.

Thanks

mattnewark left a reply on Deploying Laravel • 9 months ago

Hi @jdunsmore

Yes I am

mattnewark started a new conversation Deploying Laravel • 9 months ago

Good Morning All,

I am trying to deploy my site and I have followed the below guide so that I am hiding the core code above the public_html folder:

http://novate.co.uk/deploy-laravel-5-on-shared-hosting-from-heart-internet/

The issue that I have now is when I SSH into the folder and try and run the artisan command it doesn't work. I go to the folder core folder and try to run the queue:listen command and it seems to ignore the request. I run php artisan and it doesn't work either, no error.

Can someone please point me in the right direction

Thanks

4th December, 2017

mattnewark left a reply on Arranging Data From A Particular Column In The DB • 9 months ago

Hi,

With help from a few others on larachat, I have done it like this:

public function show($postcode)
    {
        $postcode = str_replace(' ','', $postcode);
        $postcode1 = str_limit($postcode, 5, '');
        $sites = Site::where('spostcode', 'LIKE',  '%'.$postcode1.'%')->orderByRaw("case when spostcode = '{$postcode}' then 1 else 2 end")->get();
        return Fractal::collection($sites, new SiteTransformer);
    }

mattnewark left a reply on Arranging Data From A Particular Column In The DB • 9 months ago

So far I have got this working, I know it isn't the best as I am connecting to the DB twice but i will continue to work through it and find a better option:

public function show($postcode)
    {
        $postcode = str_replace(' ','', $postcode);
        $postcode1 = str_limit($postcode, 5, '');

        $sites1 = Site::where('spostcode', $postcode)->get();
        $sites2 = Site::where('spostcode', 'LIKE',  '%'.$postcode1.'%')->where('spostcode', '<>', $postcode)->get();
        $sites = $sites1->merge($sites2);

        return Fractal::collection($sites, new SiteTransformer);
    }

mattnewark left a reply on Arranging Data From A Particular Column In The DB • 9 months ago

Hi @lostdreamer_nl,

Thanks for your reply, I think that it is working but it is placing the ones at the bottom of the list, how can we have them to the top?

I have tried to use sortBy but this did not work..

Thanks

mattnewark started a new conversation Arranging Data From A Particular Column In The DB • 9 months ago

Hi All,

What I am trying to do is get all the rows from a DB, once I have them then I would like to get the the ones with a particular column first. I can see that this is a little confusing but here is my code:

public function show($postcode)
    {
        $postcode = str_replace(' ','', $postcode);
        $postcode1 = str_limit($postcode, 5, '');

        $sites = Site::where('spostcode', 'LIKE',  '%'.$postcode1.'%')->get();

        return Fractal::collection($sites, new SiteTransformer);
    }

So what I am doing is passing the full postcode to the function and then limiting it to the first 5 characters, which will also bring the ones that match the full postcode as well in the collection. What I need to do is get the ones that match fully to be at the top of the collection.

Can someone please point me in the right direction.

Thanks

30th November, 2017

mattnewark started a new conversation Laravel Passport And SSL • 9 months ago

Hello All,

I am trying to use SSL in passport and I keep getting a unauthenticated response from the API. If I remove the https and only use http it works fine. Has anyone else had the same issue and if so did you resolve it?

Thanks

24th November, 2017

mattnewark left a reply on Return JSON From Multi Level DB • 9 months ago

Ok, so after a little more research I have now got the answer:

$stream = Wastestream::with(['Containertypes.Containersizes.Containerunits'])->get();
        return $stream;

mattnewark started a new conversation Return JSON From Multi Level DB • 9 months ago

Hello All,

I am trying to do the following with the JSON return:

[  
  {  
     "Stream":{  
        "id":1,
         "name":"Cardboard and Paper Recycling",
         "containertypes":[  
           {  
              "id":37,
               "name":"Front End Loader",
               "pivot":{  
                 "Wastestreams_id":1,
                  "Containertypes_id":37
               },
               "containersize":[  
                 {  
                    "id":32,
                     "name":"1100",
                     "containerunit":[  
                       {  
                          "id":44,
                           "name":"L"
                        }
                     ]
                  }
               ]
            }
     ]
      }
   }
]

but what i am getting is:

 {
        "Stream": {
            "id": 1,
            "name": "Cardboard and Paper Recycling",
            "containertypes": [
                {
                    "id": 37,
                    "name": "Front End Loader",
                    "pivot": {
                        "Wastestreams_id": 1,
                        "Containertypes_id": 37
                    }
                },]}
     "Types": [
            {
                "id": 37,
                "name": "Front End Loader",
                "pivot": {
                    "Wastestreams_id": 1,
                    "Containertypes_id": 37
                }
            }}]
}

My tables are as follows, ``` Containersize, Containertypes, Containerunits,Wastestream``` and the pivot tables are ```Containersizes_Containerunits, Containertypes_Containersizes, Containertypes_Wastestreams```
The models are:
Wastestream:

class Wastestream extends Model { protected $table = 'Wastestreams';

public function Containertypes()
{
    return $this->belongsToMany(Containertype::class, 'Containertypes_Wastestreams','Wastestreams_id','Containertypes_id');
}

public function Wastesubstreams()
{
    return $this->hasMany(Wastesubstream::class,'Wastestreams_id');
}

}

Containertype:

class Containertype extends Model { protected $table = 'Containertypes';

public function Containersizes()
{
    return $this->belongsToMany(Containersize::class, 'Containertypes_Containersizes', 'Containertypes_id', 'Containersizes_id');
}
public function Wastestreams()
{
    return $this->belongsToMany(Wastestream::class, 'Containertypes_Wastestreams','Containertypes_id','Wastestreams_id');
}

}

Containersize:

class Containersize extends Model { protected $table = 'Containersizes';

public function Containertypes()
{
    return $this->belongsToMany(Containertype::class, 'Containertypes_Containersizes', 'Containertypes_id', 'Containersizes_id'); 
}
public function Containerunits()
{
    return $this->belongsToMany(Containerunits::class, 'Containersizes_Containerunits', 'Containersizes_id', 'Containerunits_id');
}

}

Containerunit:

class Containerunit extends Model { protected $table = 'Containerunits';

public function Containersizes()
{
    return $this->belongsToMany(Containersize::class, 'Containersizes_Containerunits', 'Containersizes_id', 'Containerunits_id' );
}

}


In my controller I have the below:

public function GetContainerTypes() { $stream = Wastestream::orderBy('name')->get(); return Fractal::collection($stream, new AuditItemStreamTransformer); }

and in the first Transformer I have:

public function transform(Wastestream $stream) {

    return [

        'Stream' => $stream,
        'Types' => $stream->Containertypes,
    ];
}

public function includetype(Wastestream $stream)
{   
    return $this->collection($stream->Containertypes, new AuditItemSizeTransformer);
}
In the size transformer I have:

public function transform(Containertype $type) { return [

        'Sizes' => $type->Containersizes,
        
    ];
}

public function includeunit(Containertype $type)
{   
    return $this->collection($type->Containerunits, new AuditItemUnitsTransformer);
}
and in the units Transformer:

public function transform(Container $unit) { return [

        'unit' => $unit,
        
    ];
}

If some one could help get the return correct using what I have with DB's that would be wonderful.

Thanks

9th November, 2017

mattnewark left a reply on Flagged Enum • 10 months ago

Hi @Cronix

So are you saying that in the table you would have numbers from 0-6 so if it was Monday and Friday you would have 1 and 5? And so on? And then when you call those numbers back you split them and get the assigned days?

Thanks

mattnewark started a new conversation Flagged Enum • 10 months ago

Hi Everyone,

I am trying to find the best way of having days in a column in the DB, at present for ease we have created 7 columns Monday, Tuesday etc that either have a 1 or a 0, but I was wondering if there is a better way in Laravel that would only have 1 column with all the details like the C# flagged Enum.

Thanks

3rd November, 2017

mattnewark left a reply on Filtering Values With A Key Collection • 10 months ago

Hi @KrzysztofNiepokojczycki,

Thank you for getting back to me, I have been doing this all afternoon and I finally figured it out at the same time you posted. This is what I have, there is a little bit more to what I originally asked for:

$isDeleted = $audit->showItemLast;
            $isDeletedcol = $isDeleted->unique('ParentAuditItemId')->values();
        $isActive = $audit->audititems;
            $audititem = $isDeletedcol->merge($isActive)->all();
            return Fractal::includes('audititemimages')->collection($audititem, new AuditItemTransformer);

I have had to change the model as well to the below:

public function audititems()
    {
        return $this->hasMany(SiteAuditItem::class , 'SiteAudits_id', 'id')->where('isDeleted', null)->orderBy('ParentAuditItemId');
    }
    public function showItemLast()
    {
        return $this->hasMany(SiteAuditItem::class , 'SiteAudits_id', 'id')->orderBy('id', 'desc');
    }

Thanks again.

2nd November, 2017

mattnewark started a new conversation Filtering A Collection • 10 months ago

Good Afternoon all,

I am trying to get the last item in a collection so the scenario goes,

I have a audititem table that has a list of items, when a user clicks delete, the row is flagged as deleted. What I would like to do is be able to bring back the last deleted item to the user.

So so far I have the below:

public function showItemLast(SiteAudit $audit)
    {
        $audit = $audit->showItemLast->where('isDeleted', 1)
                                        ->groupBy('ParentAuditItemId')
                                        ->all();
        return $audit;       
    }

I pass the Audit id to the API and the get the items for that particular audit as shown above.

my audit model looks like:

public function showItemLast()
    {
        return $this->hasMany(SiteAuditItem::class , 'SiteAudits_id', 'id');
    }

It groups all the items based on their parent, what I would like to do is get the last deleted item, I have a created_at column so I can use the time but they do go in id order so it can be the last id of the parentid group.

I will need to put a transformer in when I have it getting the right data.

Hope that makes sense.

Thanks

20th October, 2017

mattnewark left a reply on Many To Many Relationships • 11 months ago

Hi @tykus

I have worked it out and it was an issue on one of the relationships.

Thank you so much for your help

mattnewark left a reply on Many To Many Relationships • 11 months ago

Hi @tykus

I have done the below on the transformer:

dd($AuditItem->images);

and I get the below:

Collection {#261
  #items: []
}
Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.