Our Black Friday sale is now live! All individual subscriptions are 50% OFF. This week only!

anonymouse703

anonymouse703

Member Since 2 Years Ago

Experience Points
7,930
Total
Experience

2,070 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
3
Lessons
Completed
Best Reply Awards
2
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 2
7,930 XP
Nov
06
2 weeks ago
Activity icon

Replied to Image Not Change In Saving In Database

I forgot to add that one thanks....

Activity icon

Started a new Conversation Image Not Change In Saving In Database

I have the right request payload but the pic is not updating in database... this code is okay on my other project using vue but in my pure laravel doesn't work

This is the Log of the request

[2020-11-06 05:27:06] local.INFO: array (
  '_method' => 'put',
  '_token' => 'EjbLfKXSSjzIoY3kFmyyKM7mY090SEsVF2puGrTH',
  'profile_pic' => 'rey_boy.jpg',
  'last_name' => 'Enga',
  'first_name' => 'Rey ',
  'middle_name' => 'Enriquez',
  'position' => 'Software Developer',
  'teacher_desc' => 'Good in coding',
)  

and this the controller

\Log::info($request->all());
        
        // $request->validate([
        //     // 'title' => 'required',
        //     // 'description' => 'required',
        //     'profile_pic' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:5100',
        //     ]);

        // If edit has new file
        if ($request->hasFile('profile_pic'))
        {
            //Get original filename
            $fileName = $request->profile_pic->getClientOriginalName();
            // Concat file name add time
            $concat = time()."_".$fileName;
            // Move file to public folder images
            $request->profile_pic->move(public_path('images'),$concat);
            // Assign new file name to News model for update
            $teacher->profile_pic = $concat;
                           
        }

        // Update some fields
        $teacher->last_name = $request->last_name;
        $teacher->first_name = $request->first_name;
        $teacher->middle_name = $request->middle_name;
        $teacher->position = $request->position;
        $teacher->teacher_desc = $request->teacher_desc;
        // Save the changes
        $teacher->save();
          
        session()->flash('updated', 'Teachers Content Updated.');
        return redirect()->route('teacher.index');

I commented the validation because it will not working if I uncomment the validation.

Sep
30
1 month ago
Activity icon

Replied to New Update Image Not Sent In Request In Vue Js

Ahh okay sir @kkhicher1 Thank you. by the way can you help me about this problem sir? I'm just a newbee learning Vue. https://laracasts.com/discuss/channels/vue/how-to-hide-button-if-status-is-1-and-hide-if-status-0

Activity icon

Awarded Best Reply on Image Turn Tmp 'C:\wamp64\tmp\php1124.tmp' On Update

I Changed the syntax to this

public function update(Request $request, News $news)
    {

        \Log::info($request->all());
        
        $request->validate([
            // 'news_image' => 'required', // Remove news image, this field is optional
            'title' => 'required',
            'description' => 'required',
            'news_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:5100',
            ]);

        // If edit has new file
        if ($request->hasFile('news_image'))
        {
            //Get original filename
            $fileName = $request->news_image->getClientOriginalName();
            // Concat file name add time
            $concat = time()."_".$fileName;
            // Move file to public folder news_images
            $request->news_image->move(public_path().'news_images',$concat);
            // Assign new file name to News model for update
            $news->news_image = $concat;
                           
        }
        // Update some fields
        $news->title = $request->title;
        $news->description = $request->description;
        // Save the changes
        $news->save();
    }
Activity icon

Replied to Image Turn Tmp 'C:\wamp64\tmp\php1124.tmp' On Update

I Changed the syntax to this

public function update(Request $request, News $news)
    {

        \Log::info($request->all());
        
        $request->validate([
            // 'news_image' => 'required', // Remove news image, this field is optional
            'title' => 'required',
            'description' => 'required',
            'news_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:5100',
            ]);

        // If edit has new file
        if ($request->hasFile('news_image'))
        {
            //Get original filename
            $fileName = $request->news_image->getClientOriginalName();
            // Concat file name add time
            $concat = time()."_".$fileName;
            // Move file to public folder news_images
            $request->news_image->move(public_path().'news_images',$concat);
            // Assign new file name to News model for update
            $news->news_image = $concat;
                           
        }
        // Update some fields
        $news->title = $request->title;
        $news->description = $request->description;
        // Save the changes
        $news->save();
    }
Activity icon

Started a new Conversation Image Turn Tmp 'C:\wamp64\tmp\php1124.tmp' On Update

Hello guys, store and update is almost the same but when I updating the image the image in the database is turning into tmp C:\wamp64\tmp\php1124.tmp and not the image file.. what is wrong with this?

public function update(Request $request, News $news)
    {

        \Log::info($request->all());

        $request->validate([
            'title' => 'required',
            'description' => 'required',
            'news_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:5100',
            ]);
            
           $imageName = $request->news_image->getClientOriginalName();
           $concat    = time().'_'.$imageName;

           if($request->hasFile('news_image')) {

            $news->news_image = $concat;
            $request->news_image->move(public_path('news_images'), $concat);

           }

           $news->update($request->all());
    }

By the way I'm using Laravel 7

Activity icon

Awarded Best Reply on New Update Image Not Sent In Request In Vue Js

@kkhicher1 is this the right way sir?

 let newsData = new FormData();
      formData.append('_method','PUT');
      newsData.append('news_image',this.image);

axios.put('api/news'+this.form.id,'NewsData)
.then((response)=>{
              console.log(response); //news_image here is the old image
              swal.fire({
                icon: 'success',
                title: 'News updated successfully'
              })

              this.getNewsList();

              $('#add_news_modal').modal('hide');
          })
          .catch(()=>{
            console.log("Error.....")
          })
      }
Sep
29
1 month ago
Activity icon

Replied to New Update Image Not Sent In Request In Vue Js

@kkhicher1 is this the right way sir?

 let newsData = new FormData();
      formData.append('_method','PUT');
      newsData.append('news_image',this.image);

axios.put('api/news'+this.form.id,'NewsData)
.then((response)=>{
              console.log(response); //news_image here is the old image
              swal.fire({
                icon: 'success',
                title: 'News updated successfully'
              })

              this.getNewsList();

              $('#add_news_modal').modal('hide');
          })
          .catch(()=>{
            console.log("Error.....")
          })
      }
Activity icon

Started a new Conversation New Update Image Not Sent In Request In Vue Js

Hello guys, I don't understand this kind of bug or maybe I do it wrong. When I edit a record in the modal input text are being updated but not the input file

When I upload the image to be updated the console.log is given me the right image but when I console the response console.log(response) the old image was sent.

I tried to put watcher but still the old image is sent and not the new one in the request

this is the code.

watch:{
      image:function(val){
        this.image = val;
      }
      
    },
data(){
	return{
	image: null
	form: new Form({
          news_image: '',
        }),
}
},
imageSelected(e){
        this.image = e.target.files[0];

        let reader = new FileReader();
        reader.readAsDataURL(this.image);
        reader.onload = e => {
          this.imagepreview = e.target.result;
        };
      },

updateNews(){

      let newsData = new FormData();
      newsData.append('news_image',this.image);

      console.log(this.image); //this is the image

      this.form.put('api/news/'+this.form.id ,newsData)
          .then((response)=>{
              console.log(response); //news_image here is the old image
              swal.fire({
                icon: 'success',
                title: 'News updated successfully'
              })

              this.getNewsList();

              $('#add_news_modal').modal('hide');
          })
          .catch(()=>{
            console.log("Error.....")
          })
      }
Activity icon

Replied to How To Hide Button If Status Is 1 And Hide If Status 0?

@usaandi yes but the data is from what I mounted.. that's why my condition is v-if="news.post_status == 1 it's from <tr v-for="news in newslist" :key="news.id"></tr>

data(){
      return {
        newslist: { },
    },
 mounted(){
      this.getNewsList();  
      // console.log(this.newslist);
    },
method:{
getNewsList(){
        // axios.get('/api/news').then(response => this.newslist = response.data);
        axios.get('/api/news').then((response) =>{
          this.newslist = response.data;
          // console.log(this.newslist);
        } );
      },
updateStatusPost(id){
        // console.log(id);
        axios.post('api/news-post/'+id).then(reposnse =>{
          console.log(id);
          this.getNewsList();
          swal.fire({
                icon: 'success',
                title: 'News posted successfully'
              })
        });
      },
      updateStatusUnPost(id){
        axios.post('api/news-unpost/'+id).then(reposnse =>{
          this.getNewsList();
          swal.fire({
                icon: 'success',
                title: 'News unposted successfully'
              })
        });
      }
}

I don't know if it will automatically read the changes or not after hitting the post/unpost button.

Sep
28
1 month ago
Activity icon

Replied to How To Hide Button If Status Is 1 And Hide If Status 0?

@usaandi I'm sorry I changed the field name... what I mean on my post is to toggle the two button if post_status = 1 the unpost button will display and the post button will hide and if the post_status = 0 the post button will display and the unpost button will hide. because right now the two button is displayed

Activity icon

Replied to Cannot Update Image (file Type) In Database On Updating Record.

@laracoft I will post here the code and the consoles

this what my vue script

data(){
      return {
        image: null,
        imagepreview: null,
        editmode: false,
        newslist: {},
        form: new Form({
          id : '',  
          title: '',
          description:'',
          news_image: '',
        }),
      }
    },
methods:{
       editNews(news){
        this.editmode = true;
        this.form.reset();
        this.form.fill(news);
        $('#add_news_modal').modal('show');
      },
      updateNews(){
      

      let newsData = new FormData();
      newsData.append('title',this.form.title);
      newsData.append('description',this.form.description);
      data.append('news_image',this.image);

      console.log(this.image);

      this.form.put('api/news/'+this.form.id ,newsData)
          .then((response)=>{
              console.log(response);
              swal.fire({
                icon: 'success',
                title: 'News updated successfully'
              })

              this.getNewsList();

              $('#add_news_modal').modal('hide');
          })
          .catch(()=>{
            console.log("Error.....")
          })
      },
      OpenModalNews(){
          document.getElementById("news_image").value = "";
          this.imagepreview = null;
          this.editmode = false;
          this.form.reset();
          $('#add_news_modal').modal('show');
      },
      imageSelected(e){
        this.image = e.target.files[0];

        let reader = new FileReader();
        reader.readAsDataURL(this.image);
        reader.onload = e => {
          this.imagepreview = e.target.result;
        };
      },
    }

So I tried to update the image with the name of admin.png . In the update() when I console.log(this.image); this is the result

File {name: "admin.png", lastModified: 1551762783156, 
lastModifiedDate: Tue Mar 05 2019 13:13:03 GMT+0800 (Taipei Standard Time), 
webkitRelativePath: "", size: 4550, …}
lastModified: 1551762783156
lastModifiedDate: Tue Mar 05 2019 13:13:03 GMT+0800 (Taipei Standard Time) {}
name: "admin.png"size: 4550type: "image/png"
webkitRelativePath: ""
__proto__: File

but when I console the response console.log(response); this is are data

data: "{"id":7,"title":"News 2","description":"Second News of the day","news_image":"1601168470_desktop_icon_png_382435.png"}"

See the admin.png did not pass and old value/image was the one that pass "news_image":"1601168470_desktop_icon_png_382435.png"

That's where I stuck... and by the way... I only used one modal for create,edit and update on this.

Activity icon

Replied to How To Hide Button If Status Is 1 And Hide If Status 0?

@ekpono

this is the data from console

created_at: "2020-09-25T20:20:31.000000Z"
description: "news in the mornin"
id: 1
news_image: "1601094031_4695405942_0fa1fde373_b.jpg"
post_status: 1
title: "News 1"
updated_at: "2020-09-27T03:58:31.000000Z"
Activity icon

Replied to How To Hide Button If Status Is 1 And Hide If Status 0?

@piljac1 All right I will post the codes here for you to have a reference.

Here the is where I get my news list and mounted

 getNewsList(){
        // axios.get('/api/news').then(response => this.newslist = response.data);
        axios.get('/api/news').then((response) =>{
          this.newslist = response.data;
          console.log(this.newslist);
        } );
      },
mounted(){
      this.getNewsList();  
      
    },

this is the data from console

created_at: "2020-09-25T20:20:31.000000Z"
description: "news in the mornin"
id: 1
news_image: "1601094031_4695405942_0fa1fde373_b.jpg"
post_status: 1
title: "News 1"
updated_at: "2020-09-27T03:58:31.000000Z"

and this is where I display the data from the newslist

<tbody>
    <tr v-for="news in newslist" :key="news.id">
    <td>{{news.title}}</td>
    <td>{{news.description}}</td>
    <td class="text-right align-middle">

        <template v-if="news.status == 0 || news.status == null">
        <button  class="btn btn-info m-1"  title="Post"  @click="updateStatusPost(news.id)" ><i class="glyphicon glyphicon-upload" small></i></button>
        </template>
        
        <template v-if="news.status == 1">
        <button  class="btn btn-info m-1" title="Unpost"  @click="updateStatusUnPost(news.id)" ><i class="glyphicon glyphicon-download" small></i></button>
        </template>

    </td>

    <td class="text-right align-middle">
        <button type="button" class="btn btn-primary " @click="editNews(news)" >
            <i class="fa fa-edit"></i>
            &nbsp;Edit
        </button>


        <button class="btn btn-danger delete-news" @click="deleteNews(news.id)">
            <i class="fa fa-trash"></i>
            &nbsp;Delete
        </button>
    </td>
    </tr>

</tbody>
Sep
26
2 months ago
Activity icon

Started a new Conversation How To Watch Input Type File And Pass New Data?

Hello guys newbee here, I tried to update record with image... When I click submit all the changes data sent to the controller except for the image.

The image sent to the controller is still the old one and not the updated one.

<div class="form-group">
         <label>News Image</label>
         <input type="file"  @change="imageSelected" name="news_image" id="news_image" 
          class="form-control" :class="{ 'is-invalid': form.errors.has('news_image') }" required>
          <has-error :form="form" field="news_image"></has-error>
</div>   
 
<div v-if="imagepreview" class="mt-3">
         <img :src="imagepreview" class="figure-img img-fluid" style="max-height:100px;">
  </div>

the data, image selected and update function

data(){
      return {
        image: null,
        imagepreview: null,
        editmode: false,
        newslist: {},
        form: new Form({
          id : '',  
          title: '',
          description:'',
          news_image: '',
        }),
      }
    },

imageSelected(e){
 
	this.image = e.target.files[0];

        let reader = new FileReader();
        reader.readAsDataURL(this.image);
        reader.onload = e => {
          this.imagepreview = e.target.result;
         };
},      
updateNews(){

      let data = new FormData();
      data.append('title',this.form.title);
      data.append('description',this.form.description);
      data.append('news_image',this.image);

      this.form.put('api/news/'+this.form.id ,data)
          .then((response)=>{
              console.log(response);
              swal.fire({
                icon: 'success',
                title: 'News updated successfully'
              })

              this.getNewsList();

              $('#add_news_modal').modal('hide');
          })
          .catch(()=>{
            console.log("Error.....")
          })
      },
Activity icon

Replied to Cannot Update Image (file Type) In Database On Updating Record.

@laracoft

I figured out the problem.... when I console the response data I noticed that the new selected image is not passing and the old image was retain...

here is my vue..

imageSelected(e){
        this.news_image = e.target.files[0];

        let reader = new FileReader();
        reader.readAsDataURL(this.news_image);
        reader.onload = e => {
          this.imagepreview = e.target.result;
          // this.news_image = e.target.result;
        };
      },

updateNews(){
      
      let data = new FormData();
      data.append('title',this.form.title);
      data.append('description',this.form.description);
      data.append('news_image',this.news_image);

      this.form.put('api/news/'+this.form.id ,data)
          .then((response)=>{
              console.log(response);
              swal.fire({
                icon: 'success',
                title: 'News updated successfully'
              })

              this.getNewsList();

              $('#add_news_modal').modal('hide');
          })
          .catch(()=>{
            console.log("Error.....")
          })
      },

Now what should be the proper way to pass the name of the new pic and replace the other one?

Activity icon

Replied to How To Hide Button If Status Is 1 And Hide If Status 0?

@ekpono The value of the status is 1 and 0 sir... what is the proper structure above sir?

this is my new code... but the button is not hiding when the value in the database is 1

<template v-if="news.status == 0 || news.status == null">
                    <button  class="btn btn-info m-1"  title="Post"  @click="updateStatusPost(news.id)" ><i class="glyphicon glyphicon-upload" small></i></button>
                  </template>
                  <template v-else-if="news.status == 1">
                    <button  class="btn btn-info m-1" title="Unpost"  @click="updateStatusUnPost(news.id)" ><i class="glyphicon glyphicon-download" small></i></button>
                  </template>
Activity icon

Replied to Cannot Update Image (file Type) In Database On Updating Record.

@laracoft I got data on request.. what I don't understand is the image doesn't changed after update..

Activity icon

Started a new Conversation Cannot Update Image (file Type) In Database On Updating Record.

Hi guys newbee here. Actually I have two error on updating the record

  1. is when I used the validator I got error 422 Unprocessable Entity
  2. is title and description was updated but not the image in the database

so this is the validator but I commented it because it will caused the erro

$this->validate($request, [
            'title' => 'required',
            'description' => 'required',
            'news_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:5100'
        ]);

and this is the update function but the image is not updated in the database

if ($request->hasFile('image'))
        {
                $file = $request->file('news_image');
                $timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString()); 
                $name = $timestamp. '-' .$file->getClientOriginalName();
                $data->image = $name;
                $file->move(public_path().'news_images', $name);   
                $data->save();                  
            } 

I hope someone can help me figure it out been stuck for 2 days now. Thank you in advance.

Activity icon

Replied to How To Hide Button If Status Is 1 And Hide If Status 0?

@piljac1 doesn't work sir.. What I want to do is like in pure laravel..

the situation is like this... I have status in the database and I want to hide post/unpost button based on the value of the status from database

ex.

if status = 1 then, I want to show this (post button) and hide the unpost button <button class="btn btn-info m-1" title="Post" ><i class="glyphicon glyphicon-upload" small></i></button>

then if status = 0 I want to show the unpost button and hide the post button <button class="btn btn-info m-1" title="UnPost" ><i class="glyphicon glyphicon-upload" small></i></button>

and I have that code above but don't know it's the right way

Sep
25
2 months ago
Activity icon

Replied to How To Hide Button If Status Is 1 And Hide If Status 0?

I already read it what I'm getting hard is on how to hide the button else show it.... based on my code given above I used conditional rendering but it's not working maybe it's not the right way that's I ask you the right way...but

This is already v-if and v-else-if but what I don't understand is on how to toggle the buttons (show and hide) based on the value of the status

<template v-if="news.status === 0 || news.status === null">
  	<button  class="btn btn-info m-1"  title="Post" @click="updateStatusPost(news.id)" ><i class="glyphicon glyphicon-upload" small></i></button>
   </template>

 <template v-else-if="news.status === 1">
 	<button  class="btn btn-info m-1" title="Unpost" @click="updateStatusUnPost(news.id)" ><i class="glyphicon glyphicon-download" small></i></button>
  </template>
Activity icon

Replied to How To Hide Button If Status Is 1 And Hide If Status 0?

@jlrdw how to do it sir? sorry but I'm just newbee in vue..

Activity icon

Started a new Conversation How To Hide Button If Status Is 1 And Hide If Status 0?

Hello guys, newbee here.. I have two buttons post and unpost. I want to hide the button if status is 1 and then button will show vice versa.

I don't know if it's right to put it in template.


  <template v-if="news.status === 0 || news.status === null">
  	<button  class="btn btn-info m-1"  title="Post" @click="updateStatusPost(news.id)" ><i class="glyphicon glyphicon-upload" small></i></button>
   </template>

 <template v-else-if="news.status === 1">
 	<button  class="btn btn-info m-1" title="Unpost" @click="updateStatusUnPost(news.id)" ><i class="glyphicon glyphicon-download" small></i></button>
  </template>

Activity icon

Replied to How To Update Status Using Vue?

@piljac1 thank you sir I forgot to put id on my button...

Activity icon

Started a new Conversation How To Update Status Using Vue?

Hello guys newbee here.... I know how to do this in pure laravel but in vue I really don't have an idea yet. I want to update status to 1 or 0 but it not work

vue function

updateStatusPost(id){
        axios.post('api/news-post/'+id).then(reposnse =>{
          console.log(id);
          swal.fire({
                icon: 'success',
                title: 'News posted successfully'
              })
        });
      },
      updateStatusUnPost(id){
        axios.post('api/news-unpost/'+id).then(reposnse =>{
          swal.fire({
                icon: 'success',
                title: 'News unposted successfully'
              })
        });
      }

I have data in the console

created_at: (...)
description: (...)
id: 5
news_image: (...)
post_status: (...)
title: (...)
updated_at: (...)

api route

route::post('news-post/{id}','[email protected]');
route::post('news-unpost/{id}','[email protected]');

my controller

public function postNews($id){

        \Log::info($id);

        News::whereid($id)->update([
            'post_status' => 1
        ]);
    }

    public function unpostNews($id){

        \Log::info($id);

        News::whereid($id)->update([
            'post_status' => 0
        ]);
    }
Activity icon

Replied to 422 Unprocessable Entity On Updating Record With Image

@tykus

<template>
  <div class="row">
    <div class="col-md-12 col-sm-12">
      <div class="box">
        <div class="box-header with-border">
           <button type="button" class="btn btn-primary" @click="OpenModalNews">
              <i class="fa fa-plus"></i> Add News
          </button>
        </div>
        <!-- /.box-header -->
        <div class="box-body">
          <table class="table table-striped table-bordered dt-responsive nowrap dataTable no-footer dtr-inline collapsed" cellspacing="0" width="100%" role="grid" aria-describedby="datatable-responsive_info" style="width: 100%;">
            <thead>
              <tr>
                <th>Date</th>
                <th>Title</th>
                <th class="text-center align-middle">Status</th>
                <th class="text-center align-middle">Action</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="news in newslist" :key="news.id">
                <td>{{news.title}}</td>
                <td>{{news.description}}</td>
                <td class="text-right align-middle">
                  <template v-if="news.status == 0 || news.status == null">
                    <button  class="btn btn-info m-1"  title="Post"><i class="glyphicon glyphicon-upload" small></i></button>
                  </template>
                  <template v-else>
                    <button  class="btn btn-info m-1" title="Unpost" ><i class="glyphicon glyphicon-download" small></i></button>
                  </template>
                </td>
                <td class="text-right align-middle">
                    <button type="button" class="btn btn-primary " @click="editNews(news)" >
                      <i class="fa fa-edit"></i>
                      &nbsp;Edit
                    </button>


                    <button class="btn btn-danger delete-news" @click="deleteNews(news.id)">
                      <i class="fa fa-trash"></i>
                      &nbsp;Delete
                    </button>
                </td>
              </tr>

            </tbody>
          </table>
        </div>
        <!-- /.box-body -->
      </div>
    </div>

    <!-- The Modal -->
    <div class="modal fade" id="add_news_modal">
      <div class="modal-dialog">
        <div class="modal-content">
           <form @submit.prevent="editmode ? updateNews() : addNews()" @keydown="form.onKeydown($event)" enctype="multipart/form-data">
              <!-- Modal Header -->
              <div class="modal-header">
                <h4 class="modal-title" v-show="!editmode">Add new news</h4>
                <h4 class="modal-title" v-show="editmode">Update news info</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
              </div>
              
              <!-- Modal body -->
              <div class=" modal-body">
                
                  <div class="form-group">
                    <label>Title</label>
                    <input v-model="form.title" type="text" name="title"
                      class="form-control" :class="{ 'is-invalid': form.errors.has('title') }" required>
                    <has-error :form="form" field="title"></has-error>
                  </div>
                  <div class="form-group">
                    <label>Description</label>
                    <input v-model="form.description" type="text" name="description"
                      class="form-control" :class="{ 'is-invalid': form.errors.has('description') }" required>
                    <has-error :form="form" field="description"></has-error>
                  </div>
                   <div class="form-group">
                    <label>News Image</label>
                    <input type="file"  @change="imageSelected"   ref="fileInput" name="news_image" id="news_image"
                      class="form-control" :class="{ 'is-invalid': form.errors.has('news_image') }" required>
                    <has-error :form="form" field="news_image"></has-error>
                  </div>    
                  <div v-if="imagepreview" class="mt-3">
                    <img :src="imagepreview" class="figure-img img-fluid" style="max-height:100px;">
                  </div>         
              </div>
              
              <!-- Modal footer -->
              <div class="modal-footer">
                <div class="form-group pb-xl-5 pull-right">
                  <button :disabled="form.busy" v-show="!editmode" type="submit" class="btn btn-primary">Add News</button>
                  <button :disabled="form.busy" v-show="editmode" type="submit" class="btn btn-info">Update Me</button>
                </div>
              </div>
         </form>
        </div>
      </div>
    </div>
  </div>

</template>
<script>
  export default {
  
    data(){
      return {
        news_image: null,
        imagepreview: null,
        editmode: false,
        newslist: {},
        form: new Form({
          id : '',  
          title: '',
          description:'',
          news_image: '',
        }),
       
      }
    },
    mounted(){
      this.getNewsList();  
    },
    methods:{
      getNewsList(){
        axios.get('/api/news').then(response => this.newslist = response.data);
      },
       editNews(news){
        this.editmode = true;
        this.form.reset();
        this.form.fill(news);
        $('#add_news_modal').modal('show');
      },
      updateNews(){
      
      let data = new FormData();
      data.append('title',this.form.title);
      data.append('description',this.form.description);
      data.append('news_image',this.news_image);

      this.form.put('api/news/'+this.form.id ,data)
          .then((response)=>{
              console.log(response);
              swal.fire({
                icon: 'success',
                title: 'News updated successfully'
              })

              this.loadTableData()

              $('#add_news_modal').modal('hide');
          })
          .catch(()=>{
            console.log("Error.....")
          })
      },
      OpenModalNews(){
          this.editmode = false;
          this.form.reset();
          $('#add_news_modal').modal('show');
      },
      imageSelected(e){
        this.news_image = e.target.files[0];

        let reader = new FileReader();
        reader.readAsDataURL(this.news_image);
        reader.onload = e => {
          this.imagepreview = e.target.result;
        };
      },
      addNews(){

        let data = new FormData();
        data.append('title',this.form.title);
        data.append('description',this.form.description);
        data.append('news_image',this.news_image);
        
        axios.post('/api/news',data)
        .then((response)=>{
           $('#add_news_modal').modal('hide');
            this.getNewsList(); 
        })
        .catch(error => this.form.errors.record(error.response.data));

      },
      deleteNews(id){
        // alert('Deleted');
        
        swal.fire({
          title: 'Are you sure?',
          text: 'You will not be able to recover this imaginary file!',
          icon: 'warning',
          showCancelButton: true,
          confirmButtonText: 'Yes, delete it!',
          cancelButtonText: 'No, keep it'
        }).then((result) => {
          if (result.value) {
            console.log(id);
             axios.delete('api/news/'+id).then(response => {
               
               swal.fire(
                  'Deleted!',
                  'The record has been deleted.',
                  'success'
                );
                this.getNewsList();
            });
          } else if (result.dismiss === swal.DismissReason.cancel) {
            swal.fire(
              'Cancelled',
              'The record is cancelled',
              'error'
            )
          }
        })
      }
    }
  };
</script>

Create new data, edit and delete is okay... that update is where I stuck.....

Activity icon

Replied to 422 Unprocessable Entity On Updating Record With Image

@tykus I got the same error and when I console.log I have undefined.... and imageSelected is a guide for the user to see the image they upload.

Activity icon

Replied to 422 Unprocessable Entity On Updating Record With Image

@tykus This are the fields in modal

<div class=" modal-body">
                
                  <div class="form-group">
                    <label>Title</label>
                    <input v-model="form.title" type="text" name="title"
                      class="form-control" :class="{ 'is-invalid': form.errors.has('title') }" required>
                    <has-error :form="form" field="title"></has-error>
                  </div>
                  <div class="form-group">
                    <label>Description</label>
                    <input v-model="form.description" type="text" name="description"
                      class="form-control" :class="{ 'is-invalid': form.errors.has('description') }" required>
                    <has-error :form="form" field="description"></has-error>
                  </div>
                   <div class="form-group">
                    <label>News Image</label>
                    <input type="file"  @change="imageSelected"   ref="fileInput" name="news_image" id="news_image"
                      class="form-control" :class="{ 'is-invalid': form.errors.has('news_image') }" required>
                    <has-error :form="form" field="news_image"></has-error>
                  </div>    
                  <div v-if="imagepreview" class="mt-3">
                    <img :src="imagepreview" class="figure-img img-fluid" style="max-height:100px;">
                  </div>         
              </div>

and this is my data()

data(){
      return {
        news_image: null,
        imagepreview: null,
        editmode: false,
        newslist: {},
        form: new Form({
          id : '',  
          title: '',
          description:'',
          news_image: '',
        }),
       
      }
    },

and the update()

updateNews(){

        axios.put('/api/news/'+this.form.id, data)
          .then((response)=>{
           console.log(response);
          })
      },

and the controller

 public function update(Request $request, News $news)
    {

        \Log::info($request->all());
        $this->validate($request, [
            'title' => 'required',
            'description' => 'required',
            'news_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:5100'
        ]);

        $news->where("id", $request->get("id"))->update($request->all());
    }
Activity icon

Replied to 422 Unprocessable Entity On Updating Record With Image

@sinnbeck I already tried your suggestion sir but still got the error PUT http://www.bethyl-trade.test/api/news/5 422 (Unprocessable Entity)

Activity icon

Replied to 422 Unprocessable Entity On Updating Record With Image

still I update my code like this by your suggestions still got the same error PUT http://www.bethyl-trade.test/api/news/5 422 (Unprocessable Entity)

updateNews(){

        let data = new FormData();

        let file = document.getElementById('news_image').files[0];

        data.append('title',this.form.title);
        data.append('description',this.form.description);
        data.append('news_image', file);

        axios.put('/api/news/'+this.form.id, data)
          .then((response)=>{
           console.log(response);
          })
      },
Activity icon

Replied to 422 Unprocessable Entity On Updating Record With Image

there's no request on the browser... what I see the error 422 Unprocessable Entity

Activity icon

Started a new Conversation 422 Unprocessable Entity On Updating Record With Image

Hello guys, newbee here. I want to update a record with image in the modal but when I clicked the update I have this error: app.js:285 PUT http://www.bethyl-trade.test/api/news/1 422 (Unprocessable Entity)

this is my update function in vue js

 updateNews(){

        axios.put('/api/news/'+this.form.id)
          .then(res => {
            console.log(res);
          })
          .then(err => {
              console.log(err)
          })
      },

and this is my controller

\Log::info($request->all());
        $this->validate($request, [
            'title' => 'required',
            'description' => 'required',
            'news_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:5100'
        ]);

        $news->where("id", $request->get("id"))->update($request->all());

What I missing or what is wrong?

Sep
23
2 months ago
Activity icon

Started a new Conversation Record Not Deleted In Database Using SWAL In Vue Js Even Without Error

Hello guys, newbee here. I tried to delete a record using swal thought there is no error but the record is not deleted in the database. I'm using Laravel 7 and vue.

This my controller

public function destroy(MoneyTransfer $moneyTransfer)
    {
        $moneyTransfer->delete();
        \Log::info($moneyTransfer);
    }

and this is my vue delete function with swal

deleteMoneyTransfer(id){
        // alert('Deleted');
        swal.fire({
          title: 'Are you sure?',
          text: 'You will not be able to recover this imaginary file!',
          icon: 'warning',
          showCancelButton: true,
          confirmButtonText: 'Yes, delete it!',
          cancelButtonText: 'No, keep it'
        }).then((result) => {
          if (result.value) {
             this.form.delete('api/money-trans/'+id).then(()=>{
                swal.fire(
                  'Deleted!',
                  'The record has been deleted.',
                  'success'
                )
             })
          } else if (result.dismiss === swal.DismissReason.cancel) {
            swal.fire(
              'Cancelled',
              'The record is cancelled',
              'error'
            )
          }
        })
      }
Activity icon

Replied to I Have A Request Data But Doesn't Updated In My Database

okay i will post it now it on loading the data after update. by the way thank you

Activity icon

Replied to I Have A Request Data But Doesn't Updated In My Database

It's working wow..... You save my day sir.. Is it the same way on delete? by the way I have also problem on the swal... I still learning laravel + Vue now.

Activity icon

Replied to I Have A Request Data But Doesn't Updated In My Database

Here is the error Status Code: 500 Internal Server Error

[2020-09-23 07:12:14] local.ERROR: Call to a member function where() on bool {"exception":"[object] (Error(code: 0): Call to a member function where() on bool at C:\\wamp64\\www\\bethyl-trade\\app\\Http\\Controllers\\MoneyTransferController.php:95) [stacktrace]

line 95 ->where("id", $request->get("id"));

Activity icon

Replied to I Have A Request Data But Doesn't Updated In My Database

My model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class MoneyTransfer extends Model
{
    
    protected $primaryKey = 'id';
    
    protected $table = 'moneytrans';

    protected $fillable = ['name'];

}
My Controller
Activity icon

Replied to I Have A Request Data But Doesn't Updated In My Database

I didn't see this sorry... the error of this is here:

app.js:285 PUT http://www.bethyl-trade.test/api/money-trans/13 500 (Internal Server Error)

[2020-09-23 06:54:02] local.ERROR: Call to a member function where() on bool {"exception":"[object] (Error(code: 0): Call to a member function where() on bool at C:\\wamp64\\www\\bethyl-trade\\app\\Http\\Controllers\\MoneyTransferController.php:95) [stacktrace]

Activity icon

Replied to I Have A Request Data But Doesn't Updated In My Database

what class? you mean my model?

Activity icon

Replied to I Have A Request Data But Doesn't Updated In My Database

I don't know... that's the new thing in Laravel 7. here is the update

public function update(Request $request, MoneyTransfer $moneyTransfer)
    {
        $this->validate($request, [
            'name' => 'required'
        ]);

        $moneyTransfer->update($request->all());
        return ['message' => 'Updated the user info'];
        
    }

But in my other project a pure Laravel that code is working... but when I use Vue it doesn't work.

Activity icon

Replied to I Have A Request Data But Doesn't Updated In My Database

sir Laracoft suggestion $data = $moneyTransfer->update($request->all())->where("id", $request->get("id"));

Activity icon

Replied to I Have A Request Data But Doesn't Updated In My Database

I tried your code but it's still not working... do I need to check my route?

Activity icon

Replied to I Have A Request Data But Doesn't Updated In My Database

I got error 500 Internal Server Error

in the log local.ERROR: Call to a member function where() on bool {"exception":"[object] (Error(code: 0): Call to a member function where() on bool at C:\\wamp64\\www\\bethyl-trade\\app\\Http\\Controllers\\MoneyTransferController.php:88) [stacktrace]

Activity icon

Started a new Conversation I Have A Request Data But Doesn't Updated In My Database

Hello everyone newbee here... I used Laravel 7 and Vue JS.

I tried to update a record using vue js. When I log the request I have this data

[2020-09-23 04:32:47] local.INFO: array (
  'id' => 9,
  'name' => 'PS Bank',
)  

but my update is not working... this is my controller

public function update(Request $request, MoneyTransfer $moneyTransfer)
    {
        $this->validate($request, [
            'name' => 'required'
        ]);
        
        $data = $moneyTransfer->update($request->all());
        \Log::info($request->all());
    }

Do I need to include id in my fillable in the model? this is the model. protected $fillable = ['name'];

Thank you and God bless

Sep
22
2 months ago
Activity icon

Started a new Conversation How To Update Record Using Api Resource Controller And Vue Form?

Hello guys, newbee here.

I want to update a record using vue-form and api resource controller. I have request payload and the status in the network was 200 but it doesn't updated in my database.

this how I called my update.

updateMoneyTrans(){
        this.form.put('/api/money-trans/'+this.form.id)
        .then(({data})=>{
          console.log(data);
          $('#add_moneytrans').modal('hide');
          this.mounted();
        })
        .catch(()=>{
        })
      },

and this is my api link route::resource('money-trans','MoneyTransferController');

and this is my controller

public function update(Request $request, MoneyTransfer $moneyTransfer)
    {
        try {
            $this->validate($request, [
                'name' => 'required'
            ]);
            dd($request->all());
            $moneyTransfer->update($request->all());

        } catch(Exception $e) {
            session()->flush('error', $e->getMessage());
            return redirect()->back()->withInput();
        }
        return $moneyTransfer;
        session()->flash('edit', 'Plan content updated');
    }

Note: I'm using Laravel 7

Activity icon

Replied to Request Method: PUT - Status:405 Method Not Allowed In Vue Updata

I updated the function to this

 updateMoneyTrans(){
        this.form.put('/api/money-trans/'+this.form.id)
        .then(()=>{
          $('#add_moneytrans').modal('hide');
          this.mounted();
        })
        .catch(()=>{
        })
      },

I got now status 200 but It doesn't change the value in my database

This is my controller

public function update(Request $request, MoneyTransfer $moneyTransfer)
    {
        try {
            $this->validate($request, [
                'name' => 'required'
            ]);
            dd($request->all());
            $moneyTransfer->update($request->all());

        } catch(Exception $e) {
            session()->flush('error', $e->getMessage());
        }
        return $moneyTransfer;
        session()->flash('edit', 'Plan content updated');
    }
Activity icon

Replied to Request Method: PUT - Status:405 Method Not Allowed In Vue Updata

this is in the route:list api/money-trans/{money_tran}

but how to get the {id} when I'm using Laravel 7 and this is my vue JS function

data(){
      return {
        editmode: false,
        moneytranslist: {},
        form: new Form({
          id : '',  
          name: ''
        }),
       
      }
    },
updateMoneyTrans(){
        this.form.put('/api/money-trans')
        .then(()=>{

        })
        .catch(()=>{
        })
      },

and I'm using this.form.put() so it means I pass the request data

Activity icon

Started a new Conversation Request Method: PUT - Status:405 Method Not Allowed In Vue Updata

Hello guys, newbee here in laravel + vue.

I tried to update an item but when I click update I got this error 405 Method Not Allowed

this is my api route: route::resource('moneytrans','MoneyTransferController');

and this my update function:

this.form.put('/api/moneytrans')
        .then(()=>{

        })
        .catch(()=>{
        })

What do I lack?

Sep
21
2 months ago
Activity icon

Replied to Modal Is Closing (3 Seconds) When I'm In Edit Form

I don't know that happened but it seem it's okay now... is cache and view is need to be cleared? as in always?