erfan ahmad
erfan ahmad

Reputation: 49

send two or more variable from laravel controller to vue component

assume I have a Vue component like this

export default {
    created() {
        axios.get("a url").then(res => {
            console.log(res.data);
        });
    }
};

and then axios send request to this function in laravel controller

public function something()
{
    $data = Model::all();
    $comments = Comment::all();
    // here i want to send both $data and $comments to that view
    return response()->json();
}

can i send both of them? this component and function are just an example

Upvotes: 0

Views: 989

Answers (3)

Salman Zafar
Salman Zafar

Reputation: 4035

You can achieve this simply by using response method of laravel

public function something()
{
    $data=Model::all();
    $comments=Comment::all()
    return response()->json([
         'data'=> $data,
         'comments'=> $comments
       ], 200);
}

or the other way using same method

public function something()
{
        $data=Model::all();
        $comments=Comment::all()
        return response([
         'data'=> $data,
         'comments'=> $comments
        ], 200);
}

and in your component you can simply get data using

export default
{
    created()
        {
           axios.get("a url")
                .then(res=>{
                       console.log(res.data.data)
                       console.log(res.data.comments)
                    }
        }
}

Thanks

Upvotes: 1

Pranta Roy
Pranta Roy

Reputation: 11

You can simply do this

public function function()

{
    $data=Model::all();
    $comments=Comment::all()
    return response()->json([
     'data'=>$data,
     'comments'=>$comments
   ]) //here i want to send both $data and $comments to that view
}

Upvotes: 1

Mr.Throg
Mr.Throg

Reputation: 1005

Here you go you can create an associate array and send through json.

public function something()

    {
        $data=Model::all();
        $comments=Comment::all()
        return response()->json([
         'data'=>$data,
         'comments'=>$comments
       ]) //here i want to send both $data and $comments to that view
    }

In Vue you can write something like this.

export default
{
    data(){
       return {
         comments:[]
       }
    },
    created()
        {

           axios.get("a url")
                .then(res=>{
                    this.comments = [...res.data.comments] //If you are using ES6
                    }
        }
}

Upvotes: 2

Related Questions