Courses

Flutter v2 Mobile App with Laravel API

Add Category with Floating Button

Previous: Delete Category with Confirmation Dialog
avatar

I ran into another issue here where I was getting an error, but nothing was giving me feedback on the Flutter app side. I ended up going to my Laravel app and looked at the logs. You have to change your CategoryController to just store the Category with a logged in user. Here is what I did temporarily.

$category = Category::create($request->validated());
//$category = auth()->user()->categories()->create($request->validated());

Once we log in our user in the tutorial, I can go back to the other way I believe.

👍 2
😍 2
avatar

What I've done is creating token by authenticating through Postman and then adding it to global variable so it can be used before we get to the Register/Login through the app.

class ApiService {

  ApiService();

  String token = "your------toke";
  final String baseURL = "http://your-base-url:8000/api/";

  Future<List<Category>> fetchCategories() async {
    http.Response response = await http.get(
        Uri.parse(baseURL + "categories"),
        headers: {
          HttpHeaders.contentTypeHeader: 'application/json',
          HttpHeaders.acceptHeader: 'application/json',
          HttpHeaders.authorizationHeader: 'Bearer $token',
        }
    );
    print(response.body);
    List categories = jsonDecode(response.body);
    return categories.map((category) => new Category.fromJson(category)).toList();
  }
}

class Category {
  int id;
  String name;

  Category({
    required this.id,
    required this.name,
  });
  factory Category.fromJson(Map<String, dynamic> json) {
    return Category(
      id: json['id'],
      name: json['name'],
    );
  }
}
avatar
You can use Markdown
avatar
You can use Markdown