Home > Blockchain >  How can I populate this Vue select with items coming from a Laravel API?
How can I populate this Vue select with items coming from a Laravel API?

Time:01-20

I am working on a registration form consisting of a Laravel 8 API and a Vue 3 front-end.

I have this piece of code in the AuthController to register a new user:

class AuthController extends Controller
{

    public function register(Request $request) {

     $rules = [
        'first_name' => 'required|string',
        'last_name' => 'required|string',
        'email' => 'required|email|unique:users,email',
        'password' => 'required|string|confirmed',
        'country' => 'required|string',
        'accept' => 'accepted',
    ]; 

    $fields = $request->validate($rules);

    $user = User::create([
        'first_name' => $fields['first_name'],
        'last_name' => $fields['last_name'],
        'email' => $fields['email'],
        'password' => bcrypt($fields['password']),
        'country' => $fields['country']
    ]);

    $token = $user->createToken('secret-token')->plainTextToken;

    $response = [
        'user' => $user,
        'token' => $token
    ];

    return response($response, 201);
    }
}

On the front-end, I have:

const registrationForm = {
  data() {
    return {
      apiUrl: 'http://myapp.test/api',
      formSubmitted: false,
      countries: [],
      fields: {
        first_name: '',
        last_name: '',
        email: '',
        password: '',
        country: '',
      },
      errors: {},
    };
  },
  methods: {
    // get Countries
    async getCountries(){
      try {
        const response = await axios
          .get(`${this.apiUrl}/register`)
          .catch((error) => {
            console.log(error);
          });

        // Populate countries array
        this.countries = response.data;

      } catch (error) {
        console.log(error);
      }
    },

    registerUser(){
      // Do Registrarion
      axios.post(`${this.apiUrl}/register`, this.fields).then(() =>{
        // Show success message
        this.formSubmitted = true;

        // Clear the fields
        this.fields = {}

      }).catch((error) =>{
        if (error.response.status == 422) {
          this.errors = error.response.data.errors;
        }
      });
    }
  },
  async created() {
    await this.getCountries();
  }
};

Vue.createApp(registrationForm).mount("#myForm");

The objective

With the intent of replacing the "Country" form field with a drop-down list of countries, I added this above the register() method:

public $countries;

public function countries()
{
  return Country::all('id', name', 'code');
}

Also, this line above the $rules array:

$this->countries = $this->countries();

The problem

This being an API, I do not have views, so I can not do somethng like:

return view('regisrer-view', compact('countries'));

and

<select >
  @foreach ($countries as $country)
      <option value="{{$country->id}}">{{$country->name}}</option>
  @endforeach
</select>

Instead, I need the countries list in the API, so I can output in in the Vue form, like this:

<select >
    <option value="">Select your country</option>
    <option v-for="country in countries" :value="country.id">{{ country.name }}</option>
</select>

Question

How do I populate the Vue select above with the (list of) countries?

UDATE

I did this on the back-end:

public function countries()
{
    return Country::all('id', 'name', 'code');
}

and

$response = [
    'countries' => $this->countries(),
    'user' => $user,
     'token' => $token
];

On the front:

async getCountries(){
  try {
    const response = await axios
      .get(`${this.apiUrl}/register`)
      .catch((error) => {
        console.log(error);
      });

    // Populate countries array
    this.countries = response.data.countries;

    console.log(this.countries);

  } catch (error) {
    console.log(error);
  }
}

I receive a 422 (Unprocessable Content) error in Chrome's console, when I GET the register route.

Why?

CodePudding user response:

You can add parameter in response array something like 'countries' and assign variable value. Which you will get in async getCountries() as a response.

$response = [
    'user' => $user,
    'token' => $token,
    'countries' => $this->countries
];

 const response = await axios
      .get(`${this.apiUrl}/register`)
      .catch((error) => {
        console.log(error);
      });

    // Populate countries array
    this.countries = response.data.countries;

For Better understanding of API response, I suggest you should use postman.

Postman Download

  •  Tags:  
  • Related