Norbertho

Norbertho

Member Since 2 Years Ago

Experience Points
22,500
Total
Experience

2,500 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
158
Lessons
Completed
Best Reply Awards
5
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 5
22,500 XP
Aug
11
1 month ago
Activity icon

Replied to Laravel Got Stuck After Login. Laravel 5.8

@jlrdw yeah I saw that github issue page you just linked in. So as you can see I am not the only person who has this issue.. I understand that you dont experienced this problem before, but I havent changed my setup for a while and I disabled all my chrome extensions to track the issue. still now solution. Only think i can think of is that probably you are using a Mac and I am using a Win machine and maybe there are some differences, probably i will reinstall my whole system and see if it is solve this issue.

Activity icon

Replied to Laravel Got Stuck After Login. Laravel 5.8

@mboynes Hi, thanks for your answer. I dont use any extensions so in this case this could not be the problem . Problem must be somewhere else :/

Aug
09
1 month ago
Activity icon

Replied to Laravel Got Stuck After Login. Laravel 5.8

i did not modify anything. this is happening with out of the box authentication..

Activity icon

Replied to Laravel Got Stuck After Login. Laravel 5.8

I have just created a fresh Laravel app.. Ihave experience this issue every time when i open chrome in this video you will see the issue: https://youtu.be/eRwIC3r7j7I

Activity icon

Replied to Laravel Got Stuck After Login. Laravel 5.8

I have the same issue with a freshly installed Laravel app.. However i think it is somehow Chrome related because I dont experience this problem in Firefox.

Activity icon

Replied to Store Users Selected Language Option

@aurawindsurfing I know it is a feature and not a bug. I dont complain about it my question is is there any way to keep only that variable in the session ? If i save it in cookie would be the same result? Or is there a way to modify the logout function that just before it do the return redirect to the welcome page i set the language variable in the session?

Activity icon

Started a new Conversation Store Users Selected Language Option

Hi, I am creating an app.and currently I store the user selected language option in session and it works perfectly for example if user selects English language then I store the 'en' in session with the following controller:

    public function index($locale){
        App::setlocale($locale);
        session()->put('locale', $locale);
        return redirect()->back();
    }

and I do the following in a middleware:

public function handle($request, Closure $next) {
        if (session()->has('locale')) {
            App::setlocale(session()->get('locale'));
        }else{
            App::setlocale('hu');
            session()->put('locale', 'hu');
        }
        return $next($request);
    }

It works fine user can navigate trough the app back and forward and the selected language is stay as users selected. I can log in into app and the selected language option is stay as selected and stored in session. However when the user logout from the app and redirected to the welcome page then the session is reset and the selected language cleared and the default language is set. Is there any way to prevent the logout function to clear the selected language optino?

Jul
31
1 month ago
Activity icon

Replied to Vue SPA With Laravel Authentication

Thanks @jeffreyvanrossum and @doncho85 for your replies. So basically it is adviced to install vue and laravel separately, but if i want i can develop them in the same project folder too. The main point here i need to use laravel api route as a connection between vue and laravel.

Jul
30
1 month ago
Activity icon

Replied to How To Get Products Where Category Id

@michaloravec like this? it is not woking

$products = Product::whereHas('categories', function ($query) use ($id){
                $query->where('categories.id', $id);
            })
            ->with(['productimages' => function($q){
             $q->where('productimages.featured', '=', '1')->select(['id', 'image']);
            }, 'categories'])->orderBy('id', 'DESC')
            ->paginate(9);
Activity icon

Replied to How To Get Products Where Category Id

Thanks @michaloravec Yeah that was my bad a wrote it incorrectly in my question but of course i used belongsToMany on both models in my projects. However now as you can see i load productimges as well but i would like to load only the image with featured field is 1. and select only the image column. It works

$products = Product::whereHas('categories', function ($query) use ($id){
                $query->where('categories.id', $id);
            })
            ->with(['productimages' => function($q){
             $q->where('productimages.featured', '=', '1');
            }, 'categories'])->orderBy('id', 'DESC')
            ->paginate(9);

but when i try to select only the image column then it is not working

$products = Product::whereHas('categories', function ($query) use ($id){
                $query->where('categories.id', $id);
            })
            ->with(['productimages' => function($q){
             $q->where('productimages.featured', '=', '1')->select('image);
            }, 'categories'])->orderBy('id', 'DESC')
            ->paginate(9);
Activity icon

Replied to How To Get Products Where Category Id

i have found the solution:

    public function fetchproducts($catid){
        $products = Product::whereHas('categories', function ($query) use ($catid){
            $query->where('categories.id', $catid);
        })
        ->with(['productimages', 'categories'])->orderBy('id', 'DESC')
        ->paginate(9);

    
        return $products;
    }
Activity icon

Started a new Conversation How To Get Products Where Category Id

Hi, I have a products and categories and category_product tables. So i have hasMany and belongsToMany relationship between the Products and Categories. When the user clicks on the category then i send an axios request to the controller and I would like to return the products related to that category. I have something like this in my controller but I cant make it work:

    public function fetchproducts($catid){
        $products = Product::where('categories', function ($query) use ($catid){
            $query->where('id', $catid);
        })
        ->with('productimages')->orderBy('id', 'DESC')
        ->paginate(9);


        return $products;
    }
Jul
29
1 month ago
Activity icon

Started a new Conversation Vue SPA With Laravel Authentication

Hi, I am in a learning phase in learning Vue js SPA with Laravel. I watching tutorials on YouTube and all the tutorials shows that they create a new Laravel project then the create a new Vue js project with Vue CLI. But I am a bit confused why they so that? Laravel comes with vue js if I run "composer require laravel/ui" and then "php artisan ui vue" so why the they do it separately? Is it not working if I install vue with laravel?

Jul
15
2 months ago
Activity icon

Commented on Refactoring Views: Part 2

Will you publish a video about the animated rating circle as well?

Activity icon

Started a new Conversation Video About How Laracast Handling Videos

Hi, I saw your video about video.js but as I can see now you are using vimeo for hosting videos on Laracast. A tutorial about how you upload and then display videos on Laracast website would be useful. Are you using the Vimeo API to upload videos or you are uploading the videos straight on Vimeo website?

Jun
25
2 months ago
Activity icon

Replied to Can't Save Boolean Into Mysql With Laravel

Thnaks @frankielee now I just convert it in my vue js compontent to 1 or 0 and i send it that way to the controller and it works. I thought I can update the $request->completed in the controller and then use update($request->all()); You were right it not working that way. Now in my vue js componetn my code looks like this and it works.

        toggleTodo(e){
             e.completed = !e.completed
            let data = new FormData();
            data.append('_method', 'PATCH');
            if(e.completed == true){
                 data.append('completed', 1);
             }
            if(e.completed == false){
                 data.append('completed', 0);
             }
            axios.post('/api/todo/'+e.id, data).then((res) =>{
               
            }).catch((error) => {
                this.form.errors.record(error.response.data.errors)
            })
        },

Activity icon

Replied to Can't Save Boolean Into Mysql With Laravel

No i have button with v-on:click there is no input field as I only need to toggle the completed to true or false

v-on:click="toggleTodo(todo)"
Activity icon

Replied to Can't Save Boolean Into Mysql With Laravel

Actually i have my form in a vue js component, basically i have a button to trigger this method.

toggleTodo(e){
             e.completed = !e.completed
            let data = new FormData();
            data.append('_method', 'PATCH');
            data.append('completed', e.completed);
            axios.post('/api/todo/'+e.id, data).then((res) =>{
               
            }).catch((error) => {
                this.form.errors.record(error.response.data.errors)
            })
        },

Activity icon

Replied to Can't Save Boolean Into Mysql With Laravel

when i dd( $request->completed ); i get 1 but when i delete the dd and i try to update the database i receive the error above

Activity icon

Replied to Can't Save Boolean Into Mysql With Laravel

I know, as you can see i tried it with int $request->completed = 1;

Activity icon

Started a new Conversation Can't Save Boolean Into Mysql With Laravel

Hi, I am not able to save boolean into mysql database I have a the following message: "SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'true' for column

I have set the request-> completed value to 1 but i still have the error above

    public function update(Request $request, $id)
    {
        $todo = Vuejstodo::findOrFail($id);
       
       $request->completed = 1;

        $todo->update($request->all());
        $todo->save();

        return $todo;
    }
Jun
24
2 months ago
Activity icon

Started a new Conversation PDF As Image

Hi, Is there any option to display PDF files as image in laravel ? Basically i upload a PDF document and i would like to display the PDF content on my page as an image.

I wanted to use this package: https://github.com/spatie/pdf-to-image But exec() disabled on the server i use so this package is not an option for me.

Jun
16
3 months ago
Activity icon

Started a new Conversation How To Convert Associative Arrays To Indexed?

Basically i want to get from the users table only the email addresses. When i use the following code i get an associative array

  $emails = Users::select('email')->get()->toArray();

the output is :

$emails =
array:6 [
  0 => array:1 [
    "email" => "[email protected]"
  ]
  1 => array:1 [
    "email" => "[email protected]"
  ]
  2 => array:1 [
    "email" => "[email protected]"
  ]
  3 => array:1 [
    "email" => "[email protected]"
  ]
  4 => array:1 [
    "email" => "[email protected]"
  ]
  5 => array:1 [
    "email" => "[email protected]"
  ]
]

how to convert it to :

$emails = array("[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]")
Jun
15
3 months ago
Activity icon

Replied to How To Use Mailgun API To Send Emails To Multiple Users With Attachment

OMG!!! It was so easy! I literally spent more then a day installing mailgun/mailgun and different packages and testing them. Shame on me that i haven't read the documentation on the first place :/

Thanks!

Activity icon

Started a new Conversation How To Use Mailgun API To Send Emails To Multiple Users With Attachment

Hi, I am able to send emai with Mailgun API to 1 email adress but I am not sure how to sendsame email to multiple email addresses with attachment. And also i would like to send html message (view).

Has anyone have any experience on this field?

I have tried to use Bogardo/Mailgun package it would be great and easy to use, but i was not able to install this package. I think laravel 7 is not supported by this package.

Jun
12
3 months ago
Activity icon

Replied to How To Send Multiple Attachment In Laravel

Hi I am not sure if your problem sorted, but the following code is working perfectly for me, and I can send multiple attachment with the email. So here is the code:

Form:

<form action="" method="post" enctype="multipart/form-data">@csrf

    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">General Information</div>
                <div class="card-body">
                    <div class="form-group">
                
                    
                    <div id="person">

                        <select name="person" class="form-control">
                            <option value="">select</option>
                            @foreach(App\User::all() as $user)
                                <option value="{{$user->id}}">{{$user->name}}</option>
                            @endforeach
                        </select>
                    </div>
                        
                    </div>
                    <input type="file" name="file[]">
                    <div class="form-group">
                        <textarea name="body" class="form-control"></textarea>
                    </div>
                    
            <br>
            <div class="form-group">
                <button class="btn btn-primary " type="submit">Submit</button>
            </div>
        </div>
      
    </div>
</form>

My controller where i receive the post request: (I am sending the whole request to my sendmail.php

public function mailsend(Request $request)
	{

	$people = User::get();
		foreach($people as $p){
			Mail::to($p->email)
     			->send(new SendMail($request));
        	
			}
		}
		return redirect()->back();
    }

sendmail.php

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class SendMail extends Mailable
{
    use Queueable, SerializesModels;
    public $body;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($request)
    {
              $this->body = $request->body;
        	$this->attachment = $request->file;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {

	$mail = $this->subject('Mail from Real Programmer')->view('admin.emails.sendmail');
	
	if ($this->attachment) {
        foreach($this->attachment as $file)
            $mail->attach($file->getRealPath(), [
                'as' => $file->getClientOriginalName(), 
                'mime' => $file->getMimeType()
            ]);
        }
    }
}

So basically you only store the files temporary and send them.

Hope it helped to you.

Jun
11
3 months ago
Activity icon

Started a new Conversation Video Uploading

Hi guys, I would like to create website where i can upload videos and then display them on my website with video.js. Videos are usually big in file size. Is there any good practice how to upload videos with laravel on the website and save them on the server? should I use AWS or similar service to store my videos? Should be videos uploading async?

Jun
10
3 months ago
Activity icon

Awarded Best Reply on Get Comment Where Users Are Active

Found the solution

$comments= Comment::latest()->with('user')->whereHas('user', function($q){
            $q->where('status', 'active');
        })->get();
Activity icon

Replied to Get Comment Where Users Are Active

Found the solution

$comments= Comment::latest()->with('user')->whereHas('user', function($q){
            $q->where('status', 'active');
        })->get();
Activity icon

Started a new Conversation Get Comment Where Users Are Active

Hi, I have users table and i have comments table and i have created the relationship so userhasmany comments and comment belongsto user User can have active or inactive state and I would like to get a collection where with all the active users comments. Can it be done in the controller?

So basically i need the comments.

May
30
3 months ago
Activity icon

Started a new Conversation How To GroupBy Created At Year

I would like to group a collection by created at year. What i was tried to do is using carbon to get the created at year and group it by that but it is not working.

        $aktualitasok = Article::where('type', 'aktualis')->with('articleimages')->latest()->get();
        $aktualitasok = $aktualitasok->groupBy($aktualitasok['created_at']->format('Y'));

Is there any way to group articles by created at year?

May
07
4 months ago
Activity icon

Commented on Headless Livewire

Hi Kevin, I really enjoy to watch even the Laravel part of your videos. Have you got or are you planning to create a small full project course ? on Laravael + Livewire? I mean a course what we can buy or subscribed to.

May
06
4 months ago
Activity icon

Awarded Best Reply on Call To A Member Function Update() On Null

auth()->user()->profile->update(array_merge($data, $pic2 ?? []));

i think it should be profile

May
05
4 months ago
Activity icon

Replied to Design Strategies, Front End Dynamic Add Form Fields

I would use Vue.js Component to do this. For example my vue component would looks like this more or less:

<template>
<form @submit.prevent="saveForm" method="POST" >
  < div v-for="(period, index) in periods">
            <input v-model='periods.start'   type="text" >
	    <input v-model='periods.end'   type="text" >
	    <input v-model='periods.service_grade'   type="text" >

            <button type=button  @click="addNewPeriod">Add new row</button>
	<button type=button @click="deletePeriod(index)">DELETE this row</button>

</div>

</form>
</template>

<script>
export default {

    data(){
        return{
            periods:[{
		start: ' ',
		end: ' ',
		service_grade: ' ',
	}],
        }
    },

  methods: {
            saveForm(){
           
            axios.post( .....to your backend....)
},

 addNewPeriod () {
    this.periods.push({
		start: ' ',
		end: ' ',
		service_grade: ' ',
    })
  },
    deletePeriod (index) {
      this.periods.splice(index, 1)
    }
},

  }
}
</script>

I would do something like this

Activity icon

Started a new Conversation Adding And Removing Parameters From URL

Hi, I would like to filter products by multiple options for example by categories and brands. For example: user click on category laptop and also click on the color black then i would have the following URL domain.test/products/?category=laptop&color=black How can i remove category=laptop from the URL if the user clicks on the category laptop again (so basically deselect it)? How would this links for category and colors would looks like in blade view?

Activity icon

Started a new Conversation Get Categories Only If Has Products

Hi. I have Many to Many relation between Categories and Products. I would like to load only Categories has product. I am using category_product pivot table to maintain relationship

$categories = Category:: load only categories has been attached to product
May
02
4 months ago
Activity icon

Replied to Call To A Member Function Move() On Null

dd($request->all());

do this before the validation and let us know what you see(screeenshot)

Activity icon

Replied to Call To A Member Function Update() On Null

auth()->user()->profile->update(array_merge($data, $pic2 ?? []));

i think it should be profile

Activity icon

Started a new Conversation How To Filter Products By Category

Hi, I have a Vue.js component and I would like to filter the products by category. For example if user click on the bathroom category then I would like to filter the product related to bathroom. I have Many to Many relationship between the categories and products

here is the structure of my product object. Basiccaly if someone click on category with id = 4 then i would like to filter the product by products.category.id but my problem is that i have more categories related to products so somehow i should loop trouh the products and inside products loop trough the categories as well and find where category id = selected category id


products:Array[4]
0:Object
id:50
	categories:Array[4]
	0:Object
	created_at:"2020-04-30T10:10:43.000000Z"
	id:4
	name:"Nappali"
	pivot:Object
	1:Object
	2:Object
	3:Object
created_at:"2020-04-30T10:53:51.000000Z"
deep:null
name:"Ékszeres Díszdoboz"
orderable:"1"
price:"5990"
productimages:Array[5]
quantity:"1"
shortdesc:"Ékszeres Díszdoboz - Carol Fantasy"
showquantity:"0"
sizevisible:"0"
slug:"ekszeres-diszdoboz"
stockquantity:0
1:Object
2:Object
3:Object
Apr
23
4 months ago
Activity icon

Replied to Image Upload Validation

This was the only way how I was able to sort this out.

        if($request->images === "null"){
            $request->validate([
                'name' => 'required',
                'visible' => 'required',
            ]); 
        }else{
            $request->validate([
                'name' => 'required',
                'visible' => 'required',
                'images' => 'required|image|mimes:jpeg,png,jpg,gif,svg',
            ]);  
        }
Activity icon

Replied to Image Upload Validation

Thanks for the reply @ericzwart and @michaloravec i have changed my validation as you have advised but still if i dont select an image i still geting the validation error message " The images must be a file of type: jpeg, png, jpg, gif, svg."

$request->validate([
            'name' => 'required',
            'images' => 'sometimes|required|mimes:jpeg,png,jpg,gif,svg',
        ]);

This is what i ave if I dd mar request:

array:2 [
  "name" => null
  "images" => "null"
]
Activity icon

Started a new Conversation Image Upload Validation

Hi, I would like to validate image only if the user select an image. if the user dosent select any image then i dont want to validate the image. i am using this validation in my controller but it still gives me an error that he "images must be a file of type: jpeg, png, jpg, gif, svg." Any good solution?

        $request->validate([
            'name' => 'required',
            'images' => 'sometimes|nullable|mimes:jpeg,png,jpg,gif,svg',
        ]);
Apr
22
4 months ago
Activity icon

Awarded Best Reply on Vue Form Validation

literally i have done nothing to it and now it works... cant explain how

Activity icon

Replied to Vue Form Validation

literally i have done nothing to it and now it works... cant explain how

Activity icon

Started a new Conversation Vue Form Validation

Hi, I try to use form validation created by Jeffrey github link: https://github.com/laracasts/Form-Validation-Simplified I have used it before in my projects but now for some reason I cant make it work. When I receive the errors from laravel it creates the errors object then inside it creates 1 more errors object and there i have the errors, but now i cant access to the errors becouse it is 1 level deeper then it should be. here is a screenshot: https://imgur.com/a/4yBtXjt

my vue.js component

export default {

   data(){
       return{
           
        editMode: false,
           form: new Form({
           oldpassword: '',
           password: '',
           passwordConfirm: '',

            }),
       }
   },
   methods:{
            
            saveData(){
            let data = new FormData();
            data.append('oldpassword', this.form.oldpassword);
            data.append('password', this.form.password);
            data.append('password_confirmation', this.form.passwordConfirm);
            axios.post('changePassword', data).then((res)=>{
                this.oldpassword = "",
                this.password = "",
                this.passwordConfirm = "",
                this.editMode =false,
                console.log(res)
            }).catch(error => this.form.errors.record(error.response.data.errors));
        }
   },

my Form.js

class Errors {
    /**
     * Create a new Errors instance.
     */
    constructor() {
        this.errors = {};
    }


    /**
     * Determine if an errors exists for the given field.
     *
     * @param {string} field
     */
    has(field) {
        return this.errors.hasOwnProperty(field);
    }


    /**
     * Determine if we have any errors.
     */
    any() {
        return Object.keys(this.errors).length > 0;
    }


    /**
     * Retrieve the error message for a field.
     *
     * @param {string} field
     */
    get(field) {
        if (this.errors[field]) {
            return this.errors[field][0];
        }
    }


    /**
     * Record the new errors.
     *
     * @param {object} errors
     */
    record(errors) {
        this.errors = errors;
    }


    /**
     * Clear one or all error fields.
     *
     * @param {string|null} field
     */
    clear(field) {
        if (field) {
            delete this.errors[field];

            return;
        }

        this.errors = {};
    }
}


class Form {
    /**
     * Create a new Form instance.
     *
     * @param {object} data
     */
    constructor(data) {
        this.originalData = data;

        for (let field in data) {
            this[field] = data[field];
        }

        this.errors = new Errors();
    }


    /**
     * Fetch all relevant data for the form.
     */
    data() {
        let data = {};

        for (let property in this.originalData) {
            data[property] = this[property];
        }

        return data;
    }


    /**
     * Reset the form fields.
     */
    reset() {
        for (let field in this.originalData) {
            this[field] = '';
        }

        this.errors.clear();
    }


    /**
     * Send a POST request to the given URL.
     * .
     * @param {string} url
     */
    post(url) {
        return this.submit('post', url);
    }


    /**
     * Send a PUT request to the given URL.
     * .
     * @param {string} url
     */
    put(url) {
        return this.submit('put', url);
    }


    /**
     * Send a PATCH request to the given URL.
     * .
     * @param {string} url
     */
    patch(url) {
        return this.submit('patch', url);
    }


    /**
     * Send a DELETE request to the given URL.
     * .
     * @param {string} url
     */
    delete(url) {
        return this.submit('delete', url);
    }


    /**
     * Submit the form.
     *
     * @param {string} requestType
     * @param {string} url
     */
    submit(requestType, url) {
        return new Promise((resolve, reject) => {
            axios[requestType](url, this.data())
                .then(response => {
                    this.onSuccess(response.data);

                    resolve(response.data);
                })
                .catch(error => {
                    this.onFail(error.response.data);

                    reject(error.response.data);
                });
        });
    }


    /**
     * Handle a successful form submission.
     *
     * @param {object} data
     */
    onSuccess(data) {
        alert(data.message); // temporary

        this.reset();
    }


    /**
     * Handle a failed form submission.
     *
     * @param {object} errors
     */
    onFail(errors) {
        this.errors.record(errors);
    }
}

export default Form;

Activity icon

Replied to How To Return Response 422 Status And Custom Error Message

for some reason i had to go deeper: so this is my catch

.catch((errors)=>{
                console.log(errors.response.data.errors);

            })

now i get the error message

Activity icon

Replied to How To Return Response 422 Status And Custom Error Message

so I have used axios to make a post request to my controller:

saveData(){
            let data = new FormData();
            data.append('password', this.password);
            data.append('password1', this.password1);
            data.append('password2', this.password2);
            axios.post('changePassword', data).then(()=>{

            }).catch((errors)=>{
                console.log(errors);

            })
        }

Then I process it in my controller:

 public function changePassword(Request $request)
    {
        $user = Auth::user();
        if(!Hash::check($request->password, Auth::user()->password)){
            return response()->json(['errors' => 'Paasword does not match'], 422);
        }else{
            return( 'good boy');
        }
        $user->update();
        return $user;
    }

how can I console log the errors?

Activity icon

Replied to How To Return Response 422 Status And Custom Error Message

when i console.log i see this in my console:

Error: Request failed with status code 422
    at createError (app.js:699)
    at settle (app.js:960)
    at XMLHttpRequest.handleLoad (app.js:168)
Activity icon

Replied to How To Return Response 422 Status And Custom Error Message

Hi @alanholmes I have tried both, but for some reson i am not able to console.log(errors) in the axios .catch

Activity icon

Started a new Conversation How To Return Response 422 Status And Custom Error Message

Hi i would like to return a response 422 status code and a custom message to axios from laravel controller. How can i do that? I know i can do this but how to attach the 422 status code?

return response()->json([
    'errors' => 'Password does't match',
]);