0

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

3 Answers 3

2

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
                    }
        }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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
}

1 Comment

Please provde some explanation to your answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.