0

Trying different solutions, I am fooling around with

response()->json([  ]) 

To create responses that I can read in my vue / vuex application

The Laravel api function that stores a new Speler ( dutch for player ;)):

I have trouble sending the created, or found Speler-object, through the response to the vuex-store.

Tried to set the status to 202 when succesfully logged, yet the actual status sent is 200.. It is clear that I do not understand it well enough. Can anyone help and explain?

 public function store(Request $request)
    { 
        
        if (Game::where('id',$request['game_id'])->exists() ){
            if (!Speler::where('name',$request['name'])->where('game_id',$request['game_id'])->exists()){
                $newSpeler = Speler::create(
                [                
                'name' => $request['name'],
                'pass_code' => $request['pass_code'],
                'game_id' => $request['game_id']
                ])->first());
                return $newSpeler;
            }     
            elseif ( Speler::where('name',$request['name'])->where('game_id',$request['game_id'])->where('pass_code', $request['pass_code'])->exists()){
                
                $speler = Speler::where('name',$request['name'])->where('game_id',$request['game_id'])->where('pass_code', $request['pass_code']);
                return response()->json(['speler'=> $speler, 202]);
            }           
            return response()->json(['status' => 'This name is already used, pass-code is not correct', 409]);
        }            
        return response()->json([ 'status' => 'The game-pin does not exist', 403 ]); 
    }

This is called form the vuex actions:

export const addSpeler = ({commit}, formData) => {
    return new Promise((resolve, reject) => {         
                    
        fetch(`api/speler`, {
            method: 'post',
            body:formData,
        })
        .then(res => { 
            
            if (res.status === 202){
                resolve('De speler is succesfully logged on');
                commit('SET_CURRENT_SPELER', res.data.speler);
            }
            else if (res.status === 201){
                commit('SET_CURRENT_SPELER', res.data);
                resolve('De speler is succesfully added')
            }
            else {
               reject('De speler is not logged in. Name exists and does not match passcode');
            }
           
        })
        .catch(err => {
            reject(err.message)
        });

    })
} 

and this is called from a vue method:

 methods: {
       
        
        addSpeler(){

            this.errorMessage ='';
            this.spelerAdded =false;

            const formData = new FormData();
            formData.append('name', this.name);
            formData.append('pass_code',this.pass_code);
            formData.append('game_id', this.currentGame.id);

            this.$store.dispatch('addSpeler', formData )
           
            .then(res => { 
                this.spelerAdded = true;
                console.log(res.status);
            })
            .catch(err => {
                this.errorMessage = err;
                this.spelerAdded = false;
            });
        },     

mutations.js:

export const SET_CURRENT_SPELER = (state, speler) => {
    state.currentSpeler = speler;
}

state.js:

export default{
    currentGame:{},
    currentSpeler:{}
}
M.Koops
  • 145
  • 1
  • 15
  • Does this answer your question? [Laravel - Return json along with http status code](https://stackoverflow.com/questions/31131159/laravel-return-json-along-with-http-status-code) – steven7mwesigwa Nov 11 '21 at 20:59
  • 1
    Place the status code as the second parameter of the `...->json(...)` method. – steven7mwesigwa Nov 11 '21 at 21:02
  • 1
    steven7mwesigwa is right, the status goes as the second argument of the json method `return response()->json(['speler'=> $speler], 202);` (and not inside the array as you are doing). If you don't pass a second argument, the argument value is assigned to 200 by default [`json(mixed $data = [], int $status = 200, array $headers = [], int $options = 0)`](https://github.com/laravel/framework/blob/2049de73aa099a113a287587df4cc522c90961f5/src/Illuminate/Contracts/Routing/ResponseFactory.php#L46) – porloscerros Ψ Nov 12 '21 at 00:37

1 Answers1

0

The comment by porloscerros answered the question perfectly :

the status goes as the second argument of the json method return response()->json(['speler'=> $speler], 202); (and not inside the array as you are doing). If you don't pass a second argument, the argument value is assigned to 200 by default json(mixed $data = [], int $status = 200, array $headers = [], int $options = 0)

M.Koops
  • 145
  • 1
  • 15