Solution:
Try like this:
$last_new_id = 1;
foreach($categories as $category){
$category->id = $last_new_id ;
$last_new_id++;
}
foreach($books as $book){
$book->category_id = $categories->where('category',$book->category)->first()->id
}